1 /*-------------------------------------------------------------------------
4 * hinting on how to execute a query for PostgreSQL
6 * Copyright (c) 2012-2017, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8 *-------------------------------------------------------------------------
13 #include "catalog/pg_collation.h"
14 #include "catalog/pg_index.h"
15 #include "commands/prepare.h"
16 #include "mb/pg_wchar.h"
17 #include "miscadmin.h"
18 #include "nodes/nodeFuncs.h"
19 #include "nodes/params.h"
20 #include "nodes/relation.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/cost.h"
23 #include "optimizer/geqo.h"
24 #include "optimizer/joininfo.h"
25 #include "optimizer/pathnode.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/plancat.h"
28 #include "optimizer/planner.h"
29 #include "optimizer/prep.h"
30 #include "optimizer/restrictinfo.h"
31 #include "parser/analyze.h"
32 #include "parser/parsetree.h"
33 #include "parser/scansup.h"
34 #include "partitioning/partbounds.h"
35 #include "tcop/utility.h"
36 #include "utils/builtins.h"
37 #include "utils/lsyscache.h"
38 #include "utils/memutils.h"
39 #include "utils/rel.h"
40 #include "utils/snapmgr.h"
41 #include "utils/syscache.h"
42 #include "utils/resowner.h"
44 #include "catalog/pg_class.h"
46 #include "executor/spi.h"
47 #include "catalog/pg_type.h"
51 /* partially copied from pg_stat_statements */
52 #include "normalize_query.h"
55 #include "access/htup_details.h"
57 #ifdef PG_MODULE_MAGIC
61 #define BLOCK_COMMENT_START "/*"
62 #define BLOCK_COMMENT_END "*/"
63 #define HINT_COMMENT_KEYWORD "+"
64 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
65 #define HINT_END BLOCK_COMMENT_END
68 #define HINT_SEQSCAN "SeqScan"
69 #define HINT_INDEXSCAN "IndexScan"
70 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
71 #define HINT_BITMAPSCAN "BitmapScan"
72 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
73 #define HINT_TIDSCAN "TidScan"
74 #define HINT_NOSEQSCAN "NoSeqScan"
75 #define HINT_NOINDEXSCAN "NoIndexScan"
76 #define HINT_NOBITMAPSCAN "NoBitmapScan"
77 #define HINT_NOTIDSCAN "NoTidScan"
78 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
79 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
80 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
81 #define HINT_PARALLEL "Parallel"
83 #define HINT_NESTLOOP "NestLoop"
84 #define HINT_MERGEJOIN "MergeJoin"
85 #define HINT_HASHJOIN "HashJoin"
86 #define HINT_NONESTLOOP "NoNestLoop"
87 #define HINT_NOMERGEJOIN "NoMergeJoin"
88 #define HINT_NOHASHJOIN "NoHashJoin"
89 #define HINT_LEADING "Leading"
90 #define HINT_SET "Set"
91 #define HINT_ROWS "Rows"
93 #define HINT_ARRAY_DEFAULT_INITSIZE 8
95 #define hint_ereport(str, detail) \
97 ereport(pg_hint_plan_message_level, \
98 (errmsg("pg_hint_plan%s: hint syntax error at or near \"%s\"", qnostr, (str)), \
103 #define skip_space(str) \
104 while (isspace(*str)) \
109 ENABLE_SEQSCAN = 0x01,
110 ENABLE_INDEXSCAN = 0x02,
111 ENABLE_BITMAPSCAN = 0x04,
112 ENABLE_TIDSCAN = 0x08,
113 ENABLE_INDEXONLYSCAN = 0x10
118 ENABLE_NESTLOOP = 0x01,
119 ENABLE_MERGEJOIN = 0x02,
120 ENABLE_HASHJOIN = 0x04
123 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
124 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
125 ENABLE_INDEXONLYSCAN)
126 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
127 #define DISABLE_ALL_SCAN 0
128 #define DISABLE_ALL_JOIN 0
130 /* hint keyword of enum type*/
131 typedef enum HintKeyword
133 HINT_KEYWORD_SEQSCAN,
134 HINT_KEYWORD_INDEXSCAN,
135 HINT_KEYWORD_INDEXSCANREGEXP,
136 HINT_KEYWORD_BITMAPSCAN,
137 HINT_KEYWORD_BITMAPSCANREGEXP,
138 HINT_KEYWORD_TIDSCAN,
139 HINT_KEYWORD_NOSEQSCAN,
140 HINT_KEYWORD_NOINDEXSCAN,
141 HINT_KEYWORD_NOBITMAPSCAN,
142 HINT_KEYWORD_NOTIDSCAN,
143 HINT_KEYWORD_INDEXONLYSCAN,
144 HINT_KEYWORD_INDEXONLYSCANREGEXP,
145 HINT_KEYWORD_NOINDEXONLYSCAN,
147 HINT_KEYWORD_NESTLOOP,
148 HINT_KEYWORD_MERGEJOIN,
149 HINT_KEYWORD_HASHJOIN,
150 HINT_KEYWORD_NONESTLOOP,
151 HINT_KEYWORD_NOMERGEJOIN,
152 HINT_KEYWORD_NOHASHJOIN,
154 HINT_KEYWORD_LEADING,
157 HINT_KEYWORD_PARALLEL,
159 HINT_KEYWORD_UNRECOGNIZED
162 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
163 (kw == HINT_KEYWORD_INDEXSCAN || \
164 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
165 kw == HINT_KEYWORD_INDEXONLYSCAN || \
166 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
167 kw == HINT_KEYWORD_BITMAPSCAN || \
168 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
171 typedef struct Hint Hint;
172 typedef struct HintState HintState;
174 typedef Hint *(*HintCreateFunction) (const char *hint_str,
176 HintKeyword hint_keyword);
177 typedef void (*HintDeleteFunction) (Hint *hint);
178 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
179 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
180 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
181 Query *parse, const char *str);
184 #define NUM_HINT_TYPE 6
185 typedef enum HintType
187 HINT_TYPE_SCAN_METHOD,
188 HINT_TYPE_JOIN_METHOD,
195 typedef enum HintTypeBitmap
197 HINT_BM_SCAN_METHOD = 1,
201 static const char *HintTypeName[] = {
211 typedef enum HintStatus
213 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
214 HINT_STATE_USED, /* hint is used */
215 HINT_STATE_DUPLICATION, /* specified hint duplication */
216 HINT_STATE_ERROR /* execute error (parse error does not include
220 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
221 (hint)->base.state == HINT_STATE_USED)
223 static unsigned int qno = 0;
224 static unsigned int msgqno = 0;
225 static char qnostr[32];
226 static const char *current_hint_str = NULL;
228 /* common data for all hints. */
231 const char *hint_str; /* must not do pfree */
232 const char *keyword; /* must not do pfree */
233 HintKeyword hint_keyword;
236 HintDeleteFunction delete_func;
237 HintDescFunction desc_func;
238 HintCmpFunction cmp_func;
239 HintParseFunction parse_func;
242 /* scan method hints */
243 typedef struct ScanMethodHint
249 unsigned char enforce_mask;
252 typedef struct ParentIndexInfo
257 char *expression_str;
264 /* join method hints */
265 typedef struct JoinMethodHint
271 unsigned char enforce_mask;
273 Relids inner_joinrelids;
276 /* join order hints */
277 typedef struct OuterInnerRels
280 List *outer_inner_pair;
283 typedef struct LeadingHint
286 List *relations; /* relation names specified in Leading hint */
287 OuterInnerRels *outer_inner;
290 /* change a run-time parameter hints */
291 typedef struct SetHint
294 char *name; /* name of variable */
300 typedef enum RowsValueType {
301 RVT_ABSOLUTE, /* Rows(... #1000) */
302 RVT_ADD, /* Rows(... +1000) */
303 RVT_SUB, /* Rows(... -1000) */
304 RVT_MULTI, /* Rows(... *1.2) */
306 typedef struct RowsHint
313 Relids inner_joinrelids;
315 RowsValueType value_type;
320 typedef struct ParallelHint
324 char *nworkers_str; /* original string of nworkers */
325 int nworkers; /* num of workers specified by Worker */
326 bool force_parallel; /* force parallel scan */
330 * Describes a context of hint processing.
334 char *hint_str; /* original hint string */
337 int nall_hints; /* # of valid all hints */
338 int max_all_hints; /* # of slots for all hints */
339 Hint **all_hints; /* parsed all hints */
341 /* # of each hints */
342 int num_hints[NUM_HINT_TYPE];
344 /* for scan method hints */
345 ScanMethodHint **scan_hints; /* parsed scan hints */
347 /* Initial values of parameters */
348 int init_scan_mask; /* enable_* mask */
349 int init_nworkers; /* max_parallel_workers_per_gather */
350 /* min_parallel_table_scan_size*/
351 int init_min_para_tablescan_size;
352 /* min_parallel_index_scan_size*/
353 int init_min_para_indexscan_size;
354 int init_paratup_cost; /* parallel_tuple_cost */
355 int init_parasetup_cost;/* parallel_setup_cost */
357 Index parent_relid; /* inherit parent of table relid */
358 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
359 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
360 List *parent_index_infos; /* list of parent table's index */
362 JoinMethodHint **join_hints; /* parsed join hints */
363 int init_join_mask; /* initial value join parameter */
364 List **join_hint_level;
365 LeadingHint **leading_hint; /* parsed Leading hints */
366 SetHint **set_hints; /* parsed Set hints */
367 GucContext context; /* which GUC parameters can we set? */
368 RowsHint **rows_hints; /* parsed Rows hints */
369 ParallelHint **parallel_hints; /* parsed Parallel hints */
373 * Describes a hint parser module which is bound with particular hint keyword.
375 typedef struct HintParser
378 HintCreateFunction create_func;
379 HintKeyword hint_keyword;
382 /* Module callbacks */
386 static void push_hint(HintState *hstate);
387 static void pop_hint(void);
389 static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query);
390 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
391 ParamListInfo boundParams);
392 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
396 /* Scan method hint callbacks */
397 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
398 HintKeyword hint_keyword);
399 static void ScanMethodHintDelete(ScanMethodHint *hint);
400 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
401 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
402 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
403 Query *parse, const char *str);
405 /* Join method hint callbacks */
406 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
407 HintKeyword hint_keyword);
408 static void JoinMethodHintDelete(JoinMethodHint *hint);
409 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
410 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
411 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
412 Query *parse, const char *str);
414 /* Leading hint callbacks */
415 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
416 HintKeyword hint_keyword);
417 static void LeadingHintDelete(LeadingHint *hint);
418 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
419 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
420 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
421 Query *parse, const char *str);
423 /* Set hint callbacks */
424 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
425 HintKeyword hint_keyword);
426 static void SetHintDelete(SetHint *hint);
427 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
428 static int SetHintCmp(const SetHint *a, const SetHint *b);
429 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
432 /* Rows hint callbacks */
433 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
434 HintKeyword hint_keyword);
435 static void RowsHintDelete(RowsHint *hint);
436 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
437 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
438 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
439 Query *parse, const char *str);
441 /* Parallel hint callbacks */
442 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
443 HintKeyword hint_keyword);
444 static void ParallelHintDelete(ParallelHint *hint);
445 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
446 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
447 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
448 Query *parse, const char *str);
450 static void quote_value(StringInfo buf, const char *value);
452 static const char *parse_quoted_value(const char *str, char **word,
455 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
458 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
459 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
460 Index rti, RangeTblEntry *rte);
461 static void create_plain_partial_paths(PlannerInfo *root,
463 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
464 ListCell *other_rels);
465 static void make_rels_by_clauseless_joins(PlannerInfo *root,
467 ListCell *other_rels);
468 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
469 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
471 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
472 Index rti, RangeTblEntry *rte);
473 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
476 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
478 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
480 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
484 static int set_config_option_noerror(const char *name, const char *value,
485 GucContext context, GucSource source,
486 GucAction action, bool changeVal, int elevel);
487 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
489 static int set_config_int32_option(const char *name, int32 value,
493 static bool pg_hint_plan_enable_hint = true;
494 static int debug_level = 0;
495 static int pg_hint_plan_message_level = INFO;
496 /* Default is off, to keep backward compatibility. */
497 static bool pg_hint_plan_enable_hint_table = false;
499 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
500 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
501 /* (This could not be above 1) */
502 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
504 static const struct config_enum_entry parse_messages_level_options[] = {
505 {"debug", DEBUG2, true},
506 {"debug5", DEBUG5, false},
507 {"debug4", DEBUG4, false},
508 {"debug3", DEBUG3, false},
509 {"debug2", DEBUG2, false},
510 {"debug1", DEBUG1, false},
512 {"info", INFO, false},
513 {"notice", NOTICE, false},
514 {"warning", WARNING, false},
515 {"error", ERROR, false},
517 * {"fatal", FATAL, true},
518 * {"panic", PANIC, true},
523 static const struct config_enum_entry parse_debug_level_options[] = {
526 {"detailed", 2, false},
527 {"verbose", 3, false},
539 /* Saved hook values in case of unload */
540 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
541 static planner_hook_type prev_planner = NULL;
542 static join_search_hook_type prev_join_search = NULL;
543 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
545 /* Hold reference to currently active hint */
546 static HintState *current_hint_state = NULL;
549 * List of hint contexts. We treat the head of the list as the Top of the
550 * context stack, so current_hint_state always points the first element of this
553 static List *HintStateStack = NIL;
556 * Holds statement name during executing EXECUTE command. NULL for other
559 static char *stmt_name = NULL;
561 static const HintParser parsers[] = {
562 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
563 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
564 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
565 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
566 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
567 HINT_KEYWORD_BITMAPSCANREGEXP},
568 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
569 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
570 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
571 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
572 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
573 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
574 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
575 HINT_KEYWORD_INDEXONLYSCANREGEXP},
576 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
578 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
579 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
580 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
581 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
582 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
583 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
585 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
586 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
587 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
588 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
590 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
593 PLpgSQL_plugin plugin_funcs = {
597 pg_hint_plan_plpgsql_stmt_beg,
598 pg_hint_plan_plpgsql_stmt_end,
604 * Module load callbacks
609 PLpgSQL_plugin **var_ptr;
611 /* Define custom GUC variables. */
612 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
613 "Force planner to use plans specified in the hint comment preceding to the query.",
615 &pg_hint_plan_enable_hint,
623 DefineCustomEnumVariable("pg_hint_plan.debug_print",
624 "Logs results of hint parsing.",
628 parse_debug_level_options,
635 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
636 "Message level of parse errors.",
638 &pg_hint_plan_message_level,
640 parse_messages_level_options,
647 DefineCustomEnumVariable("pg_hint_plan.message_level",
648 "Message level of debug messages.",
650 &pg_hint_plan_message_level,
652 parse_messages_level_options,
659 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
660 "Let pg_hint_plan look up the hint table.",
662 &pg_hint_plan_enable_hint_table,
671 prev_post_parse_analyze_hook = post_parse_analyze_hook;
672 post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
673 prev_planner = planner_hook;
674 planner_hook = pg_hint_plan_planner;
675 prev_join_search = join_search_hook;
676 join_search_hook = pg_hint_plan_join_search;
677 prev_set_rel_pathlist = set_rel_pathlist_hook;
678 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
680 /* setup PL/pgSQL plugin hook */
681 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
682 *var_ptr = &plugin_funcs;
684 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
688 * Module unload callback
694 PLpgSQL_plugin **var_ptr;
696 /* Uninstall hooks. */
697 post_parse_analyze_hook = prev_post_parse_analyze_hook;
698 planner_hook = prev_planner;
699 join_search_hook = prev_join_search;
700 set_rel_pathlist_hook = prev_set_rel_pathlist;
702 /* uninstall PL/pgSQL plugin hook */
703 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
708 * create and delete functions the hint object
712 ScanMethodHintCreate(const char *hint_str, const char *keyword,
713 HintKeyword hint_keyword)
715 ScanMethodHint *hint;
717 hint = palloc(sizeof(ScanMethodHint));
718 hint->base.hint_str = hint_str;
719 hint->base.keyword = keyword;
720 hint->base.hint_keyword = hint_keyword;
721 hint->base.type = HINT_TYPE_SCAN_METHOD;
722 hint->base.state = HINT_STATE_NOTUSED;
723 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
724 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
725 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
726 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
727 hint->relname = NULL;
728 hint->indexnames = NIL;
729 hint->regexp = false;
730 hint->enforce_mask = 0;
732 return (Hint *) hint;
736 ScanMethodHintDelete(ScanMethodHint *hint)
742 pfree(hint->relname);
743 list_free_deep(hint->indexnames);
748 JoinMethodHintCreate(const char *hint_str, const char *keyword,
749 HintKeyword hint_keyword)
751 JoinMethodHint *hint;
753 hint = palloc(sizeof(JoinMethodHint));
754 hint->base.hint_str = hint_str;
755 hint->base.keyword = keyword;
756 hint->base.hint_keyword = hint_keyword;
757 hint->base.type = HINT_TYPE_JOIN_METHOD;
758 hint->base.state = HINT_STATE_NOTUSED;
759 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
760 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
761 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
762 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
764 hint->inner_nrels = 0;
765 hint->relnames = NULL;
766 hint->enforce_mask = 0;
767 hint->joinrelids = NULL;
768 hint->inner_joinrelids = NULL;
770 return (Hint *) hint;
774 JoinMethodHintDelete(JoinMethodHint *hint)
783 for (i = 0; i < hint->nrels; i++)
784 pfree(hint->relnames[i]);
785 pfree(hint->relnames);
788 bms_free(hint->joinrelids);
789 bms_free(hint->inner_joinrelids);
794 LeadingHintCreate(const char *hint_str, const char *keyword,
795 HintKeyword hint_keyword)
799 hint = palloc(sizeof(LeadingHint));
800 hint->base.hint_str = hint_str;
801 hint->base.keyword = keyword;
802 hint->base.hint_keyword = hint_keyword;
803 hint->base.type = HINT_TYPE_LEADING;
804 hint->base.state = HINT_STATE_NOTUSED;
805 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
806 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
807 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
808 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
809 hint->relations = NIL;
810 hint->outer_inner = NULL;
812 return (Hint *) hint;
816 LeadingHintDelete(LeadingHint *hint)
821 list_free_deep(hint->relations);
822 if (hint->outer_inner)
823 pfree(hint->outer_inner);
828 SetHintCreate(const char *hint_str, const char *keyword,
829 HintKeyword hint_keyword)
833 hint = palloc(sizeof(SetHint));
834 hint->base.hint_str = hint_str;
835 hint->base.keyword = keyword;
836 hint->base.hint_keyword = hint_keyword;
837 hint->base.type = HINT_TYPE_SET;
838 hint->base.state = HINT_STATE_NOTUSED;
839 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
840 hint->base.desc_func = (HintDescFunction) SetHintDesc;
841 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
842 hint->base.parse_func = (HintParseFunction) SetHintParse;
847 return (Hint *) hint;
851 SetHintDelete(SetHint *hint)
861 list_free(hint->words);
866 RowsHintCreate(const char *hint_str, const char *keyword,
867 HintKeyword hint_keyword)
871 hint = palloc(sizeof(RowsHint));
872 hint->base.hint_str = hint_str;
873 hint->base.keyword = keyword;
874 hint->base.hint_keyword = hint_keyword;
875 hint->base.type = HINT_TYPE_ROWS;
876 hint->base.state = HINT_STATE_NOTUSED;
877 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
878 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
879 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
880 hint->base.parse_func = (HintParseFunction) RowsHintParse;
882 hint->inner_nrels = 0;
883 hint->relnames = NULL;
884 hint->joinrelids = NULL;
885 hint->inner_joinrelids = NULL;
886 hint->rows_str = NULL;
887 hint->value_type = RVT_ABSOLUTE;
890 return (Hint *) hint;
894 RowsHintDelete(RowsHint *hint)
903 for (i = 0; i < hint->nrels; i++)
904 pfree(hint->relnames[i]);
905 pfree(hint->relnames);
908 bms_free(hint->joinrelids);
909 bms_free(hint->inner_joinrelids);
914 ParallelHintCreate(const char *hint_str, const char *keyword,
915 HintKeyword hint_keyword)
919 hint = palloc(sizeof(ScanMethodHint));
920 hint->base.hint_str = hint_str;
921 hint->base.keyword = keyword;
922 hint->base.hint_keyword = hint_keyword;
923 hint->base.type = HINT_TYPE_PARALLEL;
924 hint->base.state = HINT_STATE_NOTUSED;
925 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
926 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
927 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
928 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
929 hint->relname = NULL;
931 hint->nworkers_str = "0";
933 return (Hint *) hint;
937 ParallelHintDelete(ParallelHint *hint)
943 pfree(hint->relname);
949 HintStateCreate(void)
953 hstate = palloc(sizeof(HintState));
954 hstate->hint_str = NULL;
955 hstate->nall_hints = 0;
956 hstate->max_all_hints = 0;
957 hstate->all_hints = NULL;
958 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
959 hstate->scan_hints = NULL;
960 hstate->init_scan_mask = 0;
961 hstate->init_nworkers = 0;
962 hstate->init_min_para_tablescan_size = 0;
963 hstate->init_min_para_indexscan_size = 0;
964 hstate->init_paratup_cost = 0;
965 hstate->init_parasetup_cost = 0;
966 hstate->parent_relid = 0;
967 hstate->parent_scan_hint = NULL;
968 hstate->parent_parallel_hint = NULL;
969 hstate->parent_index_infos = NIL;
970 hstate->join_hints = NULL;
971 hstate->init_join_mask = 0;
972 hstate->join_hint_level = NULL;
973 hstate->leading_hint = NULL;
974 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
975 hstate->set_hints = NULL;
976 hstate->rows_hints = NULL;
977 hstate->parallel_hints = NULL;
983 HintStateDelete(HintState *hstate)
990 if (hstate->hint_str)
991 pfree(hstate->hint_str);
993 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
994 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
995 if (hstate->all_hints)
996 pfree(hstate->all_hints);
997 if (hstate->parent_index_infos)
998 list_free(hstate->parent_index_infos);
1002 * Copy given value into buf, with quoting with '"' if necessary.
1005 quote_value(StringInfo buf, const char *value)
1007 bool need_quote = false;
1010 for (str = value; *str != '\0'; str++)
1012 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1015 appendStringInfoCharMacro(buf, '"');
1020 for (str = value; *str != '\0'; str++)
1023 appendStringInfoCharMacro(buf, '"');
1025 appendStringInfoCharMacro(buf, *str);
1029 appendStringInfoCharMacro(buf, '"');
1033 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1037 appendStringInfo(buf, "%s(", hint->base.keyword);
1038 if (hint->relname != NULL)
1040 quote_value(buf, hint->relname);
1041 foreach(l, hint->indexnames)
1043 appendStringInfoCharMacro(buf, ' ');
1044 quote_value(buf, (char *) lfirst(l));
1047 appendStringInfoString(buf, ")");
1049 appendStringInfoChar(buf, '\n');
1053 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1057 appendStringInfo(buf, "%s(", hint->base.keyword);
1058 if (hint->relnames != NULL)
1060 quote_value(buf, hint->relnames[0]);
1061 for (i = 1; i < hint->nrels; i++)
1063 appendStringInfoCharMacro(buf, ' ');
1064 quote_value(buf, hint->relnames[i]);
1067 appendStringInfoString(buf, ")");
1069 appendStringInfoChar(buf, '\n');
1073 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1075 if (outer_inner->relation == NULL)
1082 appendStringInfoCharMacro(buf, '(');
1083 foreach(l, outer_inner->outer_inner_pair)
1088 appendStringInfoCharMacro(buf, ' ');
1090 OuterInnerDesc(lfirst(l), buf);
1093 appendStringInfoCharMacro(buf, ')');
1096 quote_value(buf, outer_inner->relation);
1100 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1102 appendStringInfo(buf, "%s(", HINT_LEADING);
1103 if (hint->outer_inner == NULL)
1110 foreach(l, hint->relations)
1115 appendStringInfoCharMacro(buf, ' ');
1117 quote_value(buf, (char *) lfirst(l));
1121 OuterInnerDesc(hint->outer_inner, buf);
1123 appendStringInfoString(buf, ")");
1125 appendStringInfoChar(buf, '\n');
1129 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1131 bool is_first = true;
1134 appendStringInfo(buf, "%s(", HINT_SET);
1135 foreach(l, hint->words)
1140 appendStringInfoCharMacro(buf, ' ');
1142 quote_value(buf, (char *) lfirst(l));
1144 appendStringInfo(buf, ")");
1146 appendStringInfoChar(buf, '\n');
1150 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1154 appendStringInfo(buf, "%s(", hint->base.keyword);
1155 if (hint->relnames != NULL)
1157 quote_value(buf, hint->relnames[0]);
1158 for (i = 1; i < hint->nrels; i++)
1160 appendStringInfoCharMacro(buf, ' ');
1161 quote_value(buf, hint->relnames[i]);
1164 appendStringInfo(buf, " %s", hint->rows_str);
1165 appendStringInfoString(buf, ")");
1167 appendStringInfoChar(buf, '\n');
1171 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1173 appendStringInfo(buf, "%s(", hint->base.keyword);
1174 if (hint->relname != NULL)
1176 quote_value(buf, hint->relname);
1178 /* number of workers */
1179 appendStringInfoCharMacro(buf, ' ');
1180 quote_value(buf, hint->nworkers_str);
1181 /* application mode of num of workers */
1182 appendStringInfoCharMacro(buf, ' ');
1183 appendStringInfoString(buf,
1184 (hint->force_parallel ? "hard" : "soft"));
1186 appendStringInfoString(buf, ")");
1188 appendStringInfoChar(buf, '\n');
1192 * Append string which represents all hints in a given state to buf, with
1193 * preceding title with them.
1196 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1197 HintStatus state, bool nolf)
1201 appendStringInfo(buf, "%s:", title);
1203 appendStringInfoChar(buf, '\n');
1206 for (i = 0; i < hstate->nall_hints; i++)
1208 if (hstate->all_hints[i]->state != state)
1211 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1215 if (nolf && nshown == 0)
1216 appendStringInfoString(buf, "(none)");
1220 * Dump contents of given hstate to server log with log level LOG.
1223 HintStateDump(HintState *hstate)
1229 elog(LOG, "pg_hint_plan:\nno hint");
1233 initStringInfo(&buf);
1235 appendStringInfoString(&buf, "pg_hint_plan:\n");
1236 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1237 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1238 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1239 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1241 elog(LOG, "%s", buf.data);
1247 HintStateDump2(HintState *hstate)
1253 elog(pg_hint_plan_message_level,
1254 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1258 initStringInfo(&buf);
1259 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1260 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1261 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1262 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1263 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1264 appendStringInfoChar(&buf, '}');
1266 ereport(pg_hint_plan_message_level,
1267 (errmsg("%s", buf.data),
1269 errhidecontext(true)));
1279 RelnameCmp(const void *a, const void *b)
1281 const char *relnamea = *((const char **) a);
1282 const char *relnameb = *((const char **) b);
1284 return strcmp(relnamea, relnameb);
1288 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1290 return RelnameCmp(&a->relname, &b->relname);
1294 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1298 if (a->nrels != b->nrels)
1299 return a->nrels - b->nrels;
1301 for (i = 0; i < a->nrels; i++)
1304 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1312 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1318 SetHintCmp(const SetHint *a, const SetHint *b)
1320 return strcmp(a->name, b->name);
1324 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1328 if (a->nrels != b->nrels)
1329 return a->nrels - b->nrels;
1331 for (i = 0; i < a->nrels; i++)
1334 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1342 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1344 return RelnameCmp(&a->relname, &b->relname);
1348 HintCmp(const void *a, const void *b)
1350 const Hint *hinta = *((const Hint **) a);
1351 const Hint *hintb = *((const Hint **) b);
1353 if (hinta->type != hintb->type)
1354 return hinta->type - hintb->type;
1355 if (hinta->state == HINT_STATE_ERROR)
1357 if (hintb->state == HINT_STATE_ERROR)
1359 return hinta->cmp_func(hinta, hintb);
1363 * Returns byte offset of hint b from hint a. If hint a was specified before
1364 * b, positive value is returned.
1367 HintCmpWithPos(const void *a, const void *b)
1369 const Hint *hinta = *((const Hint **) a);
1370 const Hint *hintb = *((const Hint **) b);
1373 result = HintCmp(a, b);
1375 result = hinta->hint_str - hintb->hint_str;
1384 parse_keyword(const char *str, StringInfo buf)
1388 while (!isspace(*str) && *str != '(' && *str != '\0')
1389 appendStringInfoCharMacro(buf, *str++);
1395 skip_parenthesis(const char *str, char parenthesis)
1399 if (*str != parenthesis)
1401 if (parenthesis == '(')
1402 hint_ereport(str, ("Opening parenthesis is necessary."));
1403 else if (parenthesis == ')')
1404 hint_ereport(str, ("Closing parenthesis is necessary."));
1415 * Parse a token from str, and store malloc'd copy into word. A token can be
1416 * quoted with '"'. Return value is pointer to unparsed portion of original
1417 * string, or NULL if an error occurred.
1419 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1422 parse_quoted_value(const char *str, char **word, bool truncate)
1427 /* Skip leading spaces. */
1430 initStringInfo(&buf);
1443 /* Double quotation must be closed. */
1447 hint_ereport(str, ("Unterminated quoted string."));
1452 * Skip escaped double quotation.
1454 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1455 * block comments) to be an object name, so users must specify
1456 * alias for such object names.
1458 * Those special names can be allowed if we care escaped slashes
1459 * and asterisks, but we don't.
1468 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1472 appendStringInfoCharMacro(&buf, *str++);
1477 hint_ereport(str, ("Zero-length delimited string."));
1484 /* Truncate name if it's too long */
1486 truncate_identifier(buf.data, strlen(buf.data), true);
1493 static OuterInnerRels *
1494 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1496 OuterInnerRels *outer_inner;
1498 outer_inner = palloc(sizeof(OuterInnerRels));
1499 outer_inner->relation = name;
1500 outer_inner->outer_inner_pair = outer_inner_list;
1506 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1508 List *outer_inner_pair = NIL;
1510 if ((str = skip_parenthesis(str, '(')) == NULL)
1515 /* Store words in parentheses into outer_inner_list. */
1516 while(*str != ')' && *str != '\0')
1518 OuterInnerRels *outer_inner_rels;
1522 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1530 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1533 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1536 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1541 (str = skip_parenthesis(str, ')')) == NULL)
1543 list_free(outer_inner_pair);
1547 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1553 parse_parentheses_Leading(const char *str, List **name_list,
1554 OuterInnerRels **outer_inner)
1557 bool truncate = true;
1559 if ((str = skip_parenthesis(str, '(')) == NULL)
1565 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1570 /* Store words in parentheses into name_list. */
1571 while(*str != ')' && *str != '\0')
1573 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1575 list_free(*name_list);
1579 *name_list = lappend(*name_list, name);
1584 if ((str = skip_parenthesis(str, ')')) == NULL)
1590 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1593 bool truncate = true;
1595 if ((str = skip_parenthesis(str, '(')) == NULL)
1600 /* Store words in parentheses into name_list. */
1601 while(*str != ')' && *str != '\0')
1603 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1605 list_free(*name_list);
1609 *name_list = lappend(*name_list, name);
1612 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1613 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1614 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1615 keyword == HINT_KEYWORD_SET)
1621 if ((str = skip_parenthesis(str, ')')) == NULL)
1627 parse_hints(HintState *hstate, Query *parse, const char *str)
1632 initStringInfo(&buf);
1633 while (*str != '\0')
1635 const HintParser *parser;
1637 /* in error message, we output the comment including the keyword. */
1638 head = (char *) str;
1640 /* parse only the keyword of the hint. */
1641 resetStringInfo(&buf);
1642 str = parse_keyword(str, &buf);
1644 for (parser = parsers; parser->keyword != NULL; parser++)
1646 char *keyword = parser->keyword;
1649 if (pg_strcasecmp(buf.data, keyword) != 0)
1652 hint = parser->create_func(head, keyword, parser->hint_keyword);
1654 /* parser of each hint does parse in a parenthesis. */
1655 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1657 hint->delete_func(hint);
1663 * Add hint information into all_hints array. If we don't have
1664 * enough space, double the array.
1666 if (hstate->nall_hints == 0)
1668 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1669 hstate->all_hints = (Hint **)
1670 palloc(sizeof(Hint *) * hstate->max_all_hints);
1672 else if (hstate->nall_hints == hstate->max_all_hints)
1674 hstate->max_all_hints *= 2;
1675 hstate->all_hints = (Hint **)
1676 repalloc(hstate->all_hints,
1677 sizeof(Hint *) * hstate->max_all_hints);
1680 hstate->all_hints[hstate->nall_hints] = hint;
1681 hstate->nall_hints++;
1688 if (parser->keyword == NULL)
1691 ("Unrecognized hint keyword \"%s\".", buf.data));
1702 * Get hints from table by client-supplied query string and application name.
1705 get_hints_from_table(const char *client_query, const char *client_application)
1707 const char *search_query =
1709 " FROM hint_plan.hints "
1710 " WHERE norm_query_string = $1 "
1711 " AND ( application_name = $2 "
1712 " OR application_name = '' ) "
1713 " ORDER BY application_name DESC";
1714 static SPIPlanPtr plan = NULL;
1716 Oid argtypes[2] = { TEXTOID, TEXTOID };
1718 char nulls[2] = {' ', ' '};
1724 bool snapshot_set = false;
1726 hint_inhibit_level++;
1728 if (!ActiveSnapshotSet())
1730 PushActiveSnapshot(GetTransactionSnapshot());
1731 snapshot_set = true;
1739 p = SPI_prepare(search_query, 2, argtypes);
1740 plan = SPI_saveplan(p);
1744 qry = cstring_to_text(client_query);
1745 app = cstring_to_text(client_application);
1746 values[0] = PointerGetDatum(qry);
1747 values[1] = PointerGetDatum(app);
1749 SPI_execute_plan(plan, values, nulls, true, 1);
1751 if (SPI_processed > 0)
1755 hints = SPI_getvalue(SPI_tuptable->vals[0],
1756 SPI_tuptable->tupdesc, 1);
1758 * Here we use SPI_palloc to ensure that hints string is valid even
1759 * after SPI_finish call. We can't use simple palloc because it
1760 * allocates memory in SPI's context and that context is deleted in
1763 buf = SPI_palloc(strlen(hints) + 1);
1771 PopActiveSnapshot();
1773 hint_inhibit_level--;
1777 hint_inhibit_level--;
1786 * Get client-supplied query string. Addtion to that the jumbled query is
1787 * supplied if the caller requested. From the restriction of JumbleQuery, some
1788 * kind of query needs special amendments. Reutrns NULL if this query doesn't
1789 * change the current hint. This function returns NULL also when something
1790 * wrong has happend and let the caller continue using the current hints.
1793 get_query_string(ParseState *pstate, Query *query, Query **jumblequery)
1795 const char *p = debug_query_string;
1798 * If debug_query_string is set, it is the top level statement. But in some
1799 * cases we reach here with debug_query_string set NULL for example in the
1800 * case of DESCRIBE message handling. We may still see a candidate
1801 * top-level query in pstate in the case.
1805 /* We don't see a query string, return NULL */
1806 if (!pstate->p_sourcetext)
1809 p = pstate->p_sourcetext;
1812 if (jumblequery != NULL)
1813 *jumblequery = query;
1815 if (query->commandType == CMD_UTILITY)
1817 Query *target_query = (Query *)query->utilityStmt;
1820 * Some CMD_UTILITY statements have a subquery that we can hint on.
1821 * Since EXPLAIN can be placed before other kind of utility statements
1822 * and EXECUTE can be contained other kind of utility statements, these
1823 * conditions are not mutually exclusive and should be considered in
1826 if (IsA(target_query, ExplainStmt))
1828 ExplainStmt *stmt = (ExplainStmt *)target_query;
1830 Assert(IsA(stmt->query, Query));
1831 target_query = (Query *)stmt->query;
1833 /* strip out the top-level query for further processing */
1834 if (target_query->commandType == CMD_UTILITY &&
1835 target_query->utilityStmt != NULL)
1836 target_query = (Query *)target_query->utilityStmt;
1839 if (IsA(target_query, DeclareCursorStmt))
1841 DeclareCursorStmt *stmt = (DeclareCursorStmt *)target_query;
1842 Query *query = (Query *)stmt->query;
1844 /* the target must be CMD_SELECT in this case */
1845 Assert(IsA(query, Query) && query->commandType == CMD_SELECT);
1846 target_query = query;
1849 if (IsA(target_query, CreateTableAsStmt))
1851 CreateTableAsStmt *stmt = (CreateTableAsStmt *) target_query;
1853 Assert(IsA(stmt->query, Query));
1854 target_query = (Query *) stmt->query;
1856 /* strip out the top-level query for further processing */
1857 if (target_query->commandType == CMD_UTILITY &&
1858 target_query->utilityStmt != NULL)
1859 target_query = (Query *)target_query->utilityStmt;
1862 if (IsA(target_query, ExecuteStmt))
1865 * Use the prepared query for EXECUTE. The Query for jumble
1866 * also replaced with the corresponding one.
1868 ExecuteStmt *stmt = (ExecuteStmt *)target_query;
1869 PreparedStatement *entry;
1871 entry = FetchPreparedStatement(stmt->name, true);
1872 p = entry->plansource->query_string;
1873 target_query = (Query *) linitial (entry->plansource->query_list);
1876 /* JumbleQuery accespts only a non-utility Query */
1877 if (!IsA(target_query, Query) ||
1878 target_query->utilityStmt != NULL)
1879 target_query = NULL;
1882 *jumblequery = target_query;
1884 /* Return NULL if the pstate is not identical to the top-level query */
1885 else if (strcmp(pstate->p_sourcetext, p) != 0)
1892 * Get hints from the head block comment in client-supplied query string.
1895 get_hints_from_comment(const char *p)
1897 const char *hint_head;
1905 /* extract query head comment. */
1906 hint_head = strstr(p, HINT_START);
1907 if (hint_head == NULL)
1909 for (;p < hint_head; p++)
1912 * Allow these characters precedes hint comment:
1914 * - alphabets which are in ASCII range
1915 * - space, tabs and new-lines
1916 * - underscores, for identifier
1917 * - commas, for SELECT clause, EXPLAIN and PREPARE
1918 * - parentheses, for EXPLAIN and PREPARE
1920 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1921 * avoid behavior which depends on locale setting.
1923 if (!(*p >= '0' && *p <= '9') &&
1924 !(*p >= 'A' && *p <= 'Z') &&
1925 !(*p >= 'a' && *p <= 'z') &&
1929 *p != '(' && *p != ')')
1933 len = strlen(HINT_START);
1938 /* find hint end keyword. */
1939 if ((tail = strstr(p, HINT_END)) == NULL)
1941 hint_ereport(head, ("Unterminated block comment."));
1945 /* We don't support nested block comments. */
1946 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1948 hint_ereport(head, ("Nested block comments are not supported."));
1952 /* Make a copy of hint. */
1954 head = palloc(len + 1);
1955 memcpy(head, p, len);
1963 * Parse hints that got, create hint struct from parse tree and parse hints.
1966 create_hintstate(Query *parse, const char *hints)
1975 /* -1 means that no Parallel hint is specified. */
1976 max_hint_nworkers = -1;
1979 hstate = HintStateCreate();
1980 hstate->hint_str = (char *) hints;
1982 /* parse each hint. */
1983 parse_hints(hstate, parse, p);
1985 /* When nothing specified a hint, we free HintState and returns NULL. */
1986 if (hstate->nall_hints == 0)
1988 HintStateDelete(hstate);
1992 /* Sort hints in order of original position. */
1993 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1996 /* Count number of hints per hint-type. */
1997 for (i = 0; i < hstate->nall_hints; i++)
1999 Hint *cur_hint = hstate->all_hints[i];
2000 hstate->num_hints[cur_hint->type]++;
2004 * If an object (or a set of objects) has multiple hints of same hint-type,
2005 * only the last hint is valid and others are ignored in planning.
2006 * Hints except the last are marked as 'duplicated' to remember the order.
2008 for (i = 0; i < hstate->nall_hints - 1; i++)
2010 Hint *cur_hint = hstate->all_hints[i];
2011 Hint *next_hint = hstate->all_hints[i + 1];
2014 * Leading hint is marked as 'duplicated' in transform_join_hints.
2016 if (cur_hint->type == HINT_TYPE_LEADING &&
2017 next_hint->type == HINT_TYPE_LEADING)
2021 * Note that we need to pass addresses of hint pointers, because
2022 * HintCmp is designed to sort array of Hint* by qsort.
2024 if (HintCmp(&cur_hint, &next_hint) == 0)
2026 hint_ereport(cur_hint->hint_str,
2027 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
2028 cur_hint->state = HINT_STATE_DUPLICATION;
2033 * Make sure that per-type array pointers point proper position in the
2034 * array which consists of all hints.
2036 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
2037 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
2038 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
2039 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
2040 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
2041 hstate->set_hints = (SetHint **) (hstate->leading_hint +
2042 hstate->num_hints[HINT_TYPE_LEADING]);
2043 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
2044 hstate->num_hints[HINT_TYPE_SET]);
2045 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
2046 hstate->num_hints[HINT_TYPE_ROWS]);
2052 * Parse inside of parentheses of scan-method hints.
2055 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
2058 const char *keyword = hint->base.keyword;
2059 HintKeyword hint_keyword = hint->base.hint_keyword;
2060 List *name_list = NIL;
2063 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2066 /* Parse relation name and index name(s) if given hint accepts. */
2067 length = list_length(name_list);
2069 /* at least twp parameters required */
2073 ("%s hint requires a relation.", hint->base.keyword));
2074 hint->base.state = HINT_STATE_ERROR;
2078 hint->relname = linitial(name_list);
2079 hint->indexnames = list_delete_first(name_list);
2081 /* check whether the hint accepts index name(s) */
2082 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
2085 ("%s hint accepts only one relation.",
2086 hint->base.keyword));
2087 hint->base.state = HINT_STATE_ERROR;
2091 /* Set a bit for specified hint. */
2092 switch (hint_keyword)
2094 case HINT_KEYWORD_SEQSCAN:
2095 hint->enforce_mask = ENABLE_SEQSCAN;
2097 case HINT_KEYWORD_INDEXSCAN:
2098 hint->enforce_mask = ENABLE_INDEXSCAN;
2100 case HINT_KEYWORD_INDEXSCANREGEXP:
2101 hint->enforce_mask = ENABLE_INDEXSCAN;
2102 hint->regexp = true;
2104 case HINT_KEYWORD_BITMAPSCAN:
2105 hint->enforce_mask = ENABLE_BITMAPSCAN;
2107 case HINT_KEYWORD_BITMAPSCANREGEXP:
2108 hint->enforce_mask = ENABLE_BITMAPSCAN;
2109 hint->regexp = true;
2111 case HINT_KEYWORD_TIDSCAN:
2112 hint->enforce_mask = ENABLE_TIDSCAN;
2114 case HINT_KEYWORD_NOSEQSCAN:
2115 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2117 case HINT_KEYWORD_NOINDEXSCAN:
2118 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2120 case HINT_KEYWORD_NOBITMAPSCAN:
2121 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2123 case HINT_KEYWORD_NOTIDSCAN:
2124 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2126 case HINT_KEYWORD_INDEXONLYSCAN:
2127 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2129 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2130 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2131 hint->regexp = true;
2133 case HINT_KEYWORD_NOINDEXONLYSCAN:
2134 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2137 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2146 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2149 const char *keyword = hint->base.keyword;
2150 HintKeyword hint_keyword = hint->base.hint_keyword;
2151 List *name_list = NIL;
2153 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2156 hint->nrels = list_length(name_list);
2158 if (hint->nrels > 0)
2164 * Transform relation names from list to array to sort them with qsort
2167 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2168 foreach (l, name_list)
2170 hint->relnames[i] = lfirst(l);
2175 list_free(name_list);
2177 /* A join hint requires at least two relations */
2178 if (hint->nrels < 2)
2181 ("%s hint requires at least two relations.",
2182 hint->base.keyword));
2183 hint->base.state = HINT_STATE_ERROR;
2187 /* Sort hints in alphabetical order of relation names. */
2188 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2190 switch (hint_keyword)
2192 case HINT_KEYWORD_NESTLOOP:
2193 hint->enforce_mask = ENABLE_NESTLOOP;
2195 case HINT_KEYWORD_MERGEJOIN:
2196 hint->enforce_mask = ENABLE_MERGEJOIN;
2198 case HINT_KEYWORD_HASHJOIN:
2199 hint->enforce_mask = ENABLE_HASHJOIN;
2201 case HINT_KEYWORD_NONESTLOOP:
2202 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2204 case HINT_KEYWORD_NOMERGEJOIN:
2205 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2207 case HINT_KEYWORD_NOHASHJOIN:
2208 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2211 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2220 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2223 if (outer_inner->outer_inner_pair == NIL)
2225 if (outer_inner->relation)
2231 if (list_length(outer_inner->outer_inner_pair) == 2)
2233 foreach(l, outer_inner->outer_inner_pair)
2235 if (!OuterInnerPairCheck(lfirst(l)))
2246 OuterInnerList(OuterInnerRels *outer_inner)
2248 List *outer_inner_list = NIL;
2250 OuterInnerRels *outer_inner_rels;
2252 foreach(l, outer_inner->outer_inner_pair)
2254 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2256 if (outer_inner_rels->relation != NULL)
2257 outer_inner_list = lappend(outer_inner_list,
2258 outer_inner_rels->relation);
2260 outer_inner_list = list_concat(outer_inner_list,
2261 OuterInnerList(outer_inner_rels));
2263 return outer_inner_list;
2267 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2270 List *name_list = NIL;
2271 OuterInnerRels *outer_inner = NULL;
2273 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2277 if (outer_inner != NULL)
2278 name_list = OuterInnerList(outer_inner);
2280 hint->relations = name_list;
2281 hint->outer_inner = outer_inner;
2283 /* A Leading hint requires at least two relations */
2284 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2286 hint_ereport(hint->base.hint_str,
2287 ("%s hint requires at least two relations.",
2289 hint->base.state = HINT_STATE_ERROR;
2291 else if (hint->outer_inner != NULL &&
2292 !OuterInnerPairCheck(hint->outer_inner))
2294 hint_ereport(hint->base.hint_str,
2295 ("%s hint requires two sets of relations when parentheses nests.",
2297 hint->base.state = HINT_STATE_ERROR;
2304 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2306 List *name_list = NIL;
2308 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2312 hint->words = name_list;
2314 /* We need both name and value to set GUC parameter. */
2315 if (list_length(name_list) == 2)
2317 hint->name = linitial(name_list);
2318 hint->value = lsecond(name_list);
2322 hint_ereport(hint->base.hint_str,
2323 ("%s hint requires name and value of GUC parameter.",
2325 hint->base.state = HINT_STATE_ERROR;
2332 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2335 HintKeyword hint_keyword = hint->base.hint_keyword;
2336 List *name_list = NIL;
2340 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2343 /* Last element must be rows specification */
2344 hint->nrels = list_length(name_list) - 1;
2346 if (hint->nrels > 0)
2352 * Transform relation names from list to array to sort them with qsort
2355 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2356 foreach (l, name_list)
2358 if (hint->nrels <= i)
2360 hint->relnames[i] = lfirst(l);
2365 /* Retieve rows estimation */
2366 rows_str = list_nth(name_list, hint->nrels);
2367 hint->rows_str = rows_str; /* store as-is for error logging */
2368 if (rows_str[0] == '#')
2370 hint->value_type = RVT_ABSOLUTE;
2373 else if (rows_str[0] == '+')
2375 hint->value_type = RVT_ADD;
2378 else if (rows_str[0] == '-')
2380 hint->value_type = RVT_SUB;
2383 else if (rows_str[0] == '*')
2385 hint->value_type = RVT_MULTI;
2390 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2391 hint->base.state = HINT_STATE_ERROR;
2394 hint->rows = strtod(rows_str, &end_ptr);
2397 hint_ereport(rows_str,
2398 ("%s hint requires valid number as rows estimation.",
2399 hint->base.keyword));
2400 hint->base.state = HINT_STATE_ERROR;
2404 /* A join hint requires at least two relations */
2405 if (hint->nrels < 2)
2408 ("%s hint requires at least two relations.",
2409 hint->base.keyword));
2410 hint->base.state = HINT_STATE_ERROR;
2414 list_free(name_list);
2416 /* Sort relnames in alphabetical order. */
2417 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2423 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2426 HintKeyword hint_keyword = hint->base.hint_keyword;
2427 List *name_list = NIL;
2431 bool force_parallel = false;
2433 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2436 /* Parse relation name and index name(s) if given hint accepts. */
2437 length = list_length(name_list);
2439 if (length < 2 || length > 3)
2442 ("wrong number of arguments (%d): %s",
2443 length, hint->base.keyword));
2444 hint->base.state = HINT_STATE_ERROR;
2448 hint->relname = linitial(name_list);
2450 /* The second parameter is number of workers */
2451 hint->nworkers_str = list_nth(name_list, 1);
2452 nworkers = strtod(hint->nworkers_str, &end_ptr);
2453 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2456 hint_ereport(hint->nworkers_str,
2457 ("number of workers must be a number: %s",
2458 hint->base.keyword));
2459 else if (nworkers < 0)
2460 hint_ereport(hint->nworkers_str,
2461 ("number of workers must be positive: %s",
2462 hint->base.keyword));
2463 else if (nworkers > max_worker_processes)
2464 hint_ereport(hint->nworkers_str,
2465 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2466 nworkers, max_worker_processes, hint->base.keyword));
2468 hint->base.state = HINT_STATE_ERROR;
2471 hint->nworkers = nworkers;
2473 /* optional third parameter is specified */
2476 const char *modeparam = (const char *)list_nth(name_list, 2);
2477 if (pg_strcasecmp(modeparam, "hard") == 0)
2478 force_parallel = true;
2479 else if (pg_strcasecmp(modeparam, "soft") != 0)
2481 hint_ereport(modeparam,
2482 ("enforcement must be soft or hard: %s",
2483 hint->base.keyword));
2484 hint->base.state = HINT_STATE_ERROR;
2488 hint->force_parallel = force_parallel;
2490 if (hint->base.state != HINT_STATE_ERROR &&
2491 nworkers > max_hint_nworkers)
2492 max_hint_nworkers = nworkers;
2498 * set GUC parameter functions
2502 get_current_scan_mask()
2507 mask |= ENABLE_SEQSCAN;
2508 if (enable_indexscan)
2509 mask |= ENABLE_INDEXSCAN;
2510 if (enable_bitmapscan)
2511 mask |= ENABLE_BITMAPSCAN;
2513 mask |= ENABLE_TIDSCAN;
2514 if (enable_indexonlyscan)
2515 mask |= ENABLE_INDEXONLYSCAN;
2521 get_current_join_mask()
2525 if (enable_nestloop)
2526 mask |= ENABLE_NESTLOOP;
2527 if (enable_mergejoin)
2528 mask |= ENABLE_MERGEJOIN;
2529 if (enable_hashjoin)
2530 mask |= ENABLE_HASHJOIN;
2536 * Sets GUC prameters without throwing exception. Reutrns false if something
2540 set_config_option_noerror(const char *name, const char *value,
2541 GucContext context, GucSource source,
2542 GucAction action, bool changeVal, int elevel)
2545 MemoryContext ccxt = CurrentMemoryContext;
2549 result = set_config_option(name, value, context, source,
2550 action, changeVal, 0, false);
2556 /* Save error info */
2557 MemoryContextSwitchTo(ccxt);
2558 errdata = CopyErrorData();
2562 (errcode(errdata->sqlerrcode),
2563 errmsg("%s", errdata->message),
2564 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2565 errdata->hint ? errhint("%s", errdata->hint) : 0));
2567 FreeErrorData(errdata);
2575 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2576 * if something wrong.
2579 set_config_int32_option(const char *name, int32 value, GucContext context)
2581 char buf[16]; /* enough for int32 */
2583 if (snprintf(buf, 16, "%d", value) < 0)
2585 ereport(pg_hint_plan_message_level,
2586 (errmsg ("Cannot set integer value: %d: %s",
2587 max_hint_nworkers, strerror(errno))));
2592 set_config_option_noerror(name, buf, context,
2593 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2594 pg_hint_plan_message_level);
2597 /* setup scan method enforcement according to given options */
2599 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2603 for (i = 0; i < noptions; i++)
2605 SetHint *hint = options[i];
2608 if (!hint_state_enabled(hint))
2611 result = set_config_option_noerror(hint->name, hint->value, context,
2612 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2613 pg_hint_plan_message_level);
2615 hint->base.state = HINT_STATE_USED;
2617 hint->base.state = HINT_STATE_ERROR;
2624 * Setup parallel execution environment.
2626 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2629 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2633 hint->base.state = HINT_STATE_USED;
2634 set_config_int32_option("max_parallel_workers_per_gather",
2635 hint->nworkers, state->context);
2638 set_config_int32_option("max_parallel_workers_per_gather",
2639 state->init_nworkers, state->context);
2641 /* force means that enforce parallel as far as possible */
2642 if (hint && hint->force_parallel && hint->nworkers > 0)
2644 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2645 set_config_int32_option("parallel_setup_cost", 0, state->context);
2646 set_config_int32_option("min_parallel_table_scan_size", 0,
2648 set_config_int32_option("min_parallel_index_scan_size", 0,
2653 set_config_int32_option("parallel_tuple_cost",
2654 state->init_paratup_cost, state->context);
2655 set_config_int32_option("parallel_setup_cost",
2656 state->init_parasetup_cost, state->context);
2657 set_config_int32_option("min_parallel_table_scan_size",
2658 state->init_min_para_tablescan_size,
2660 set_config_int32_option("min_parallel_index_scan_size",
2661 state->init_min_para_indexscan_size,
2666 #define SET_CONFIG_OPTION(name, type_bits) \
2667 set_config_option_noerror((name), \
2668 (mask & (type_bits)) ? "true" : "false", \
2669 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2673 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2674 * GUCs to the saved state in state.
2677 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2679 unsigned char enforce_mask = state->init_scan_mask;
2680 GucContext context = state->context;
2685 enforce_mask = scanhint->enforce_mask;
2686 scanhint->base.state = HINT_STATE_USED;
2689 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2690 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2691 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2693 mask = enforce_mask;
2695 mask = enforce_mask & current_hint_state->init_scan_mask;
2697 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2698 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2699 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2700 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2701 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2705 set_join_config_options(unsigned char enforce_mask, GucContext context)
2709 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2710 enforce_mask == ENABLE_HASHJOIN)
2711 mask = enforce_mask;
2713 mask = enforce_mask & current_hint_state->init_join_mask;
2715 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2716 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2717 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2721 * Push a hint into hint stack which is implemented with List struct. Head of
2722 * list is top of stack.
2725 push_hint(HintState *hstate)
2727 /* Prepend new hint to the list means pushing to stack. */
2728 HintStateStack = lcons(hstate, HintStateStack);
2730 /* Pushed hint is the one which should be used hereafter. */
2731 current_hint_state = hstate;
2734 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2738 /* Hint stack must not be empty. */
2739 if(HintStateStack == NIL)
2740 elog(ERROR, "hint stack is empty");
2743 * Take a hint at the head from the list, and free it. Switch
2744 * current_hint_state to point new head (NULL if the list is empty).
2746 HintStateStack = list_delete_first(HintStateStack);
2747 HintStateDelete(current_hint_state);
2748 if(HintStateStack == NIL)
2749 current_hint_state = NULL;
2751 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2755 * Retrieve and store a hint string from given query or from the hint table.
2756 * If we are using the hint table, the query string is needed to be normalized.
2757 * However, ParseState, which is not available in planner_hook, is required to
2758 * check if the query tree (Query) is surely corresponding to the target query.
2761 pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query)
2763 const char *query_str;
2764 MemoryContext oldcontext;
2766 if (prev_post_parse_analyze_hook)
2767 prev_post_parse_analyze_hook(pstate, query);
2769 /* do nothing under hint table search */
2770 if (hint_inhibit_level > 0)
2773 if (!pg_hint_plan_enable_hint)
2775 if (current_hint_str)
2777 pfree((void *)current_hint_str);
2778 current_hint_str = NULL;
2783 /* increment the query number */
2785 if (debug_level > 1)
2786 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2789 /* search the hint table for a hint if requested */
2790 if (pg_hint_plan_enable_hint_table)
2793 pgssJumbleState jstate;
2795 char *normalized_query = NULL;
2797 query_str = get_query_string(pstate, query, &jumblequery);
2799 /* If this query is not for hint, just return */
2803 /* clear the previous hint string */
2804 if (current_hint_str)
2806 pfree((void *)current_hint_str);
2807 current_hint_str = NULL;
2813 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2814 * careful to PostgreSQL's version up.
2816 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2817 jstate.jumble_len = 0;
2818 jstate.clocations_buf_size = 32;
2819 jstate.clocations = (pgssLocationLen *)
2820 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2821 jstate.clocations_count = 0;
2823 JumbleQuery(&jstate, jumblequery);
2826 * Normalize the query string by replacing constants with '?'
2829 * Search hint string which is stored keyed by query string
2830 * and application name. The query string is normalized to allow
2833 * Adding 1 byte to query_len ensures that the returned string has
2834 * a terminating NULL.
2836 query_len = strlen(query_str) + 1;
2838 generate_normalized_query(&jstate, query_str,
2839 query->stmt_location,
2841 GetDatabaseEncoding());
2844 * find a hint for the normalized query. the result should be in
2847 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2849 get_hints_from_table(normalized_query, application_name);
2850 MemoryContextSwitchTo(oldcontext);
2852 if (debug_level > 1)
2854 if (current_hint_str)
2855 ereport(pg_hint_plan_message_level,
2856 (errmsg("pg_hint_plan[qno=0x%x]: "
2857 "post_parse_analyze_hook: "
2858 "hints from table: \"%s\": "
2859 "normalized_query=\"%s\", "
2860 "application name =\"%s\"",
2861 qno, current_hint_str,
2862 normalized_query, application_name),
2863 errhidestmt(msgqno != qno),
2864 errhidecontext(msgqno != qno)));
2866 ereport(pg_hint_plan_message_level,
2867 (errmsg("pg_hint_plan[qno=0x%x]: "
2868 "no match found in table: "
2869 "application name = \"%s\", "
2870 "normalized_query=\"%s\"",
2871 qno, application_name,
2873 errhidestmt(msgqno != qno),
2874 errhidecontext(msgqno != qno)));
2880 /* retrun if we have hint here */
2881 if (current_hint_str)
2885 query_str = get_query_string(pstate, query, NULL);
2890 * get hints from the comment. However we may have the same query
2891 * string with the previous call, but just retrieving hints is expected
2892 * to be faster than checking for identicalness before retrieval.
2894 if (current_hint_str)
2895 pfree((void *)current_hint_str);
2897 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2898 current_hint_str = get_hints_from_comment(query_str);
2899 MemoryContextSwitchTo(oldcontext);
2902 if (debug_level > 1)
2904 if (debug_level == 1 &&
2905 (stmt_name || strcmp(query_str, debug_query_string)))
2906 ereport(pg_hint_plan_message_level,
2907 (errmsg("hints in comment=\"%s\"",
2908 current_hint_str ? current_hint_str : "(none)"),
2909 errhidestmt(msgqno != qno),
2910 errhidecontext(msgqno != qno)));
2912 ereport(pg_hint_plan_message_level,
2913 (errmsg("hints in comment=\"%s\", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2914 current_hint_str ? current_hint_str : "(none)",
2915 stmt_name, query_str, debug_query_string),
2916 errhidestmt(msgqno != qno),
2917 errhidecontext(msgqno != qno)));
2923 * Read and set up hint information
2925 static PlannedStmt *
2926 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2929 PlannedStmt *result;
2933 * Use standard planner if pg_hint_plan is disabled or current nesting
2934 * depth is nesting depth of SPI calls. Other hook functions try to change
2935 * plan with current_hint_state if any, so set it to NULL.
2937 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2939 if (debug_level > 1)
2940 ereport(pg_hint_plan_message_level,
2941 (errmsg ("pg_hint_plan%s: planner: enable_hint=%d,"
2942 " hint_inhibit_level=%d",
2943 qnostr, pg_hint_plan_enable_hint,
2944 hint_inhibit_level),
2945 errhidestmt(msgqno != qno)));
2948 goto standard_planner_proc;
2952 * Support for nested plpgsql functions. This is quite ugly but this is the
2953 * only point I could find where I can get the query string.
2955 if (plpgsql_recurse_level > 0)
2957 MemoryContext oldcontext;
2959 if (current_hint_str)
2960 pfree((void *)current_hint_str);
2962 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
2964 get_hints_from_comment((char *)error_context_stack->arg);
2965 MemoryContextSwitchTo(oldcontext);
2968 if (!current_hint_str)
2969 goto standard_planner_proc;
2971 /* parse the hint into hint state struct */
2972 hstate = create_hintstate(parse, pstrdup(current_hint_str));
2974 /* run standard planner if the statement has not valid hint */
2976 goto standard_planner_proc;
2979 * Push new hint struct to the hint stack to disable previous hint context.
2983 /* Set scan enforcement here. */
2984 save_nestlevel = NewGUCNestLevel();
2986 /* Apply Set hints, then save it as the initial state */
2987 setup_guc_enforcement(current_hint_state->set_hints,
2988 current_hint_state->num_hints[HINT_TYPE_SET],
2989 current_hint_state->context);
2991 current_hint_state->init_scan_mask = get_current_scan_mask();
2992 current_hint_state->init_join_mask = get_current_join_mask();
2993 current_hint_state->init_min_para_tablescan_size =
2994 min_parallel_table_scan_size;
2995 current_hint_state->init_min_para_indexscan_size =
2996 min_parallel_index_scan_size;
2997 current_hint_state->init_paratup_cost = parallel_tuple_cost;
2998 current_hint_state->init_parasetup_cost = parallel_setup_cost;
3001 * max_parallel_workers_per_gather should be non-zero here if Workers hint
3004 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
3005 set_config_int32_option("max_parallel_workers_per_gather",
3006 1, current_hint_state->context);
3007 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
3009 if (debug_level > 1)
3011 ereport(pg_hint_plan_message_level,
3012 (errhidestmt(msgqno != qno),
3013 errmsg("pg_hint_plan%s: planner", qnostr)));
3018 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
3019 * the state when this planner started when error occurred in planner.
3024 result = (*prev_planner) (parse, cursorOptions, boundParams);
3026 result = standard_planner(parse, cursorOptions, boundParams);
3031 * Rollback changes of GUC parameters, and pop current hint context
3032 * from hint stack to rewind the state.
3034 AtEOXact_GUC(true, save_nestlevel);
3040 /* Print hint in debug mode. */
3041 if (debug_level == 1)
3042 HintStateDump(current_hint_state);
3043 else if (debug_level > 1)
3044 HintStateDump2(current_hint_state);
3047 * Rollback changes of GUC parameters, and pop current hint context from
3048 * hint stack to rewind the state.
3050 AtEOXact_GUC(true, save_nestlevel);
3055 standard_planner_proc:
3056 if (debug_level > 1)
3058 ereport(pg_hint_plan_message_level,
3059 (errhidestmt(msgqno != qno),
3060 errmsg("pg_hint_plan%s: planner: no valid hint",
3064 current_hint_state = NULL;
3066 return (*prev_planner) (parse, cursorOptions, boundParams);
3068 return standard_planner(parse, cursorOptions, boundParams);
3072 * Find scan method hint to be applied to the given relation
3075 static ScanMethodHint *
3076 find_scan_hint(PlannerInfo *root, Index relid)
3080 ScanMethodHint *real_name_hint = NULL;
3081 ScanMethodHint *alias_hint = NULL;
3084 /* This should not be a join rel */
3086 rel = root->simple_rel_array[relid];
3089 * This function is called for any RelOptInfo or its inheritance parent if
3090 * any. If we are called from inheritance planner, the RelOptInfo for the
3091 * parent of target child relation is not set in the planner info.
3093 * Otherwise we should check that the reloptinfo is base relation or
3094 * inheritance children.
3097 rel->reloptkind != RELOPT_BASEREL &&
3098 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3102 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3104 rte = root->simple_rte_array[relid];
3107 /* We don't hint on other than relation and foreign tables */
3108 if (rte->rtekind != RTE_RELATION ||
3109 rte->relkind == RELKIND_FOREIGN_TABLE)
3112 /* Find scan method hint, which matches given names, from the list. */
3113 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3115 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3117 /* We ignore disabled hints. */
3118 if (!hint_state_enabled(hint))
3122 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3125 /* check the real name for appendrel children */
3126 if (!real_name_hint &&
3127 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3129 char *realname = get_rel_name(rte->relid);
3131 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3132 real_name_hint = hint;
3135 /* No more match expected, break */
3136 if(alias_hint && real_name_hint)
3140 /* real name match precedes alias match */
3142 return real_name_hint;
3147 static ParallelHint *
3148 find_parallel_hint(PlannerInfo *root, Index relid)
3152 ParallelHint *real_name_hint = NULL;
3153 ParallelHint *alias_hint = NULL;
3156 /* This should not be a join rel */
3158 rel = root->simple_rel_array[relid];
3161 * Parallel planning is appliable only on base relation, which has
3168 * We have set root->glob->parallelModeOK if needed. What we should do here
3169 * is just following the decision of planner.
3171 if (!rel->consider_parallel)
3175 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3177 rte = root->simple_rte_array[relid];
3180 /* Find parallel method hint, which matches given names, from the list. */
3181 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3183 ParallelHint *hint = current_hint_state->parallel_hints[i];
3185 /* We ignore disabled hints. */
3186 if (!hint_state_enabled(hint))
3190 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3193 /* check the real name for appendrel children */
3194 if (!real_name_hint &&
3195 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3197 char *realname = get_rel_name(rte->relid);
3199 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3200 real_name_hint = hint;
3203 /* No more match expected, break */
3204 if(alias_hint && real_name_hint)
3208 /* real name match precedes alias match */
3210 return real_name_hint;
3218 * Returns TRUE on match, FALSE on no match.
3220 * s1 --- the data to match against
3221 * s2 --- the pattern
3223 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3226 regexpeq(const char *s1, const char *s2)
3232 strcpy(name.data, s1);
3233 regexp = cstring_to_text(s2);
3235 result = DirectFunctionCall2Coll(nameregexeq,
3236 DEFAULT_COLLATION_OID,
3237 NameGetDatum(&name),
3238 PointerGetDatum(regexp));
3239 return DatumGetBool(result);
3243 /* Remove indexes instructed not to use by hint. */
3245 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3246 bool using_parent_hint)
3252 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3253 Oid relationObjectId = rte->relid;
3256 * We delete all the IndexOptInfo list and prevent you from being usable by
3259 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3260 hint->enforce_mask == ENABLE_TIDSCAN)
3262 list_free_deep(rel->indexlist);
3263 rel->indexlist = NIL;
3264 hint->base.state = HINT_STATE_USED;
3270 * When a list of indexes is not specified, we just use all indexes.
3272 if (hint->indexnames == NIL)
3276 * Leaving only an specified index, we delete it from a IndexOptInfo list
3280 if (debug_level > 0)
3281 initStringInfo(&buf);
3283 for (cell = list_head(rel->indexlist); cell; cell = next)
3285 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3286 char *indexname = get_rel_name(info->indexoid);
3288 bool use_index = false;
3292 foreach(l, hint->indexnames)
3294 char *hintname = (char *) lfirst(l);
3298 result = regexpeq(indexname, hintname);
3300 result = RelnameCmp(&indexname, &hintname) == 0;
3305 if (debug_level > 0)
3307 appendStringInfoCharMacro(&buf, ' ');
3308 quote_value(&buf, indexname);
3316 * Apply index restriction of parent hint to children. Since index
3317 * inheritance is not explicitly described we should search for an
3318 * children's index with the same definition to that of the parent.
3320 if (using_parent_hint && !use_index)
3322 foreach(l, current_hint_state->parent_index_infos)
3326 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3329 * we check the 'same' index by comparing uniqueness, access
3330 * method and index key columns.
3332 if (p_info->indisunique != info->unique ||
3333 p_info->method != info->relam ||
3334 list_length(p_info->column_names) != info->ncolumns)
3337 /* Check if index key columns match */
3338 for (i = 0; i < info->ncolumns; i++)
3340 char *c_attname = NULL;
3341 char *p_attname = NULL;
3343 p_attname = list_nth(p_info->column_names, i);
3346 * if both of the key of the same position are expressions,
3347 * ignore them for now and check later.
3349 if (info->indexkeys[i] == 0 && !p_attname)
3352 /* deny if one is expression while another is not */
3353 if (info->indexkeys[i] == 0 || !p_attname)
3356 c_attname = get_attname(relationObjectId,
3357 info->indexkeys[i], false);
3359 /* deny if any of column attributes don't match */
3360 if (strcmp(p_attname, c_attname) != 0 ||
3361 p_info->indcollation[i] != info->indexcollations[i] ||
3362 p_info->opclass[i] != info->opcintype[i]||
3363 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3364 != info->reverse_sort[i] ||
3365 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3366 != info->nulls_first[i])
3370 /* deny this if any difference found */
3371 if (i != info->ncolumns)
3374 /* check on key expressions */
3375 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3376 (p_info->indpred_str && (info->indpred != NIL)))
3378 /* fetch the index of this child */
3379 ht_idx = SearchSysCache1(INDEXRELID,
3380 ObjectIdGetDatum(info->indexoid));
3382 /* check expressions if both expressions are available */
3383 if (p_info->expression_str &&
3384 !heap_attisnull(ht_idx, Anum_pg_index_indexprs, NULL))
3391 * to change the expression's parameter of child's
3394 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3395 Anum_pg_index_indexprs,
3398 result = DirectFunctionCall2(pg_get_expr,
3403 /* deny if expressions don't match */
3404 if (strcmp(p_info->expression_str,
3405 text_to_cstring(DatumGetTextP(result))) != 0)
3408 ReleaseSysCache(ht_idx);
3413 /* compare index predicates */
3414 if (p_info->indpred_str &&
3415 !heap_attisnull(ht_idx, Anum_pg_index_indpred, NULL))
3421 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3422 Anum_pg_index_indpred,
3425 result = DirectFunctionCall2(pg_get_expr,
3430 if (strcmp(p_info->indpred_str,
3431 text_to_cstring(DatumGetTextP(result))) != 0)
3434 ReleaseSysCache(ht_idx);
3440 ReleaseSysCache(ht_idx);
3442 else if (p_info->expression_str || (info->indexprs != NIL))
3444 else if (p_info->indpred_str || (info->indpred != NIL))
3449 /* to log the candidate of index */
3450 if (debug_level > 0)
3452 appendStringInfoCharMacro(&buf, ' ');
3453 quote_value(&buf, indexname);
3461 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3468 if (debug_level == 1)
3470 StringInfoData rel_buf;
3471 char *disprelname = "";
3474 * If this hint targetted the parent, use the real name of this
3475 * child. Otherwise use hint specification.
3477 if (using_parent_hint)
3478 disprelname = get_rel_name(rte->relid);
3480 disprelname = hint->relname;
3483 initStringInfo(&rel_buf);
3484 quote_value(&rel_buf, disprelname);
3487 (errmsg("available indexes for %s(%s):%s",
3492 pfree(rel_buf.data);
3497 * Return information of index definition.
3499 static ParentIndexInfo *
3500 get_parent_index_info(Oid indexoid, Oid relid)
3502 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3503 Relation indexRelation;
3504 Form_pg_index index;
3508 indexRelation = index_open(indexoid, RowExclusiveLock);
3510 index = indexRelation->rd_index;
3512 p_info->indisunique = index->indisunique;
3513 p_info->method = indexRelation->rd_rel->relam;
3515 p_info->column_names = NIL;
3516 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3517 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3518 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3521 * Collect relation attribute names of index columns for index
3522 * identification, not index attribute names. NULL means expression index
3525 for (i = 0; i < index->indnatts; i++)
3527 attname = get_attname(relid, index->indkey.values[i], true);
3528 p_info->column_names = lappend(p_info->column_names, attname);
3530 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3531 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3532 p_info->indoption[i] = indexRelation->rd_indoption[i];
3536 * to check to match the expression's parameter of index with child indexes
3538 p_info->expression_str = NULL;
3539 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs,
3546 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3547 Anum_pg_index_indexprs, &isnull);
3549 result = DirectFunctionCall2(pg_get_expr,
3551 ObjectIdGetDatum(relid));
3553 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3557 * to check to match the predicate's parameter of index with child indexes
3559 p_info->indpred_str = NULL;
3560 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred,
3567 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3568 Anum_pg_index_indpred, &isnull);
3570 result = DirectFunctionCall2(pg_get_expr,
3572 ObjectIdGetDatum(relid));
3574 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3577 index_close(indexRelation, NoLock);
3583 * cancel hint enforcement
3586 reset_hint_enforcement()
3588 setup_scan_method_enforcement(NULL, current_hint_state);
3589 setup_parallel_plan_enforcement(NULL, current_hint_state);
3593 * Set planner guc parameters according to corresponding scan hints. Returns
3594 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3595 * there respectively.
3598 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3599 ScanMethodHint **rshint, ParallelHint **rphint)
3601 Index new_parent_relid = 0;
3603 ScanMethodHint *shint = NULL;
3604 ParallelHint *phint = NULL;
3605 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3606 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3609 /* reset returns if requested */
3610 if (rshint != NULL) *rshint = NULL;
3611 if (rphint != NULL) *rphint = NULL;
3614 * We could register the parent relation of the following children here
3615 * when inhparent == true but inheritnce planner doesn't call this function
3616 * for parents. Since we cannot distinguish who called this function we
3617 * cannot do other than always seeking the parent regardless of who called
3622 /* set up only parallel hints for parent relation */
3623 phint = find_parallel_hint(root, rel->relid);
3626 setup_parallel_plan_enforcement(phint, current_hint_state);
3627 if (rphint) *rphint = phint;
3628 ret |= HINT_BM_PARALLEL;
3632 if (debug_level > 1)
3633 ereport(pg_hint_plan_message_level,
3635 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3636 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3637 " current_hint_state=%p, hint_inhibit_level=%d",
3638 qnostr, relationObjectId,
3639 get_rel_name(relationObjectId),
3640 inhparent, current_hint_state, hint_inhibit_level)));
3644 /* Find the parent for this relation other than the registered parent */
3645 foreach (l, root->append_rel_list)
3647 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3649 if (appinfo->child_relid == rel->relid)
3651 if (current_hint_state->parent_relid != appinfo->parent_relid)
3652 new_parent_relid = appinfo->parent_relid;
3659 /* This relation doesn't have a parent. Cancel current_hint_state. */
3660 current_hint_state->parent_relid = 0;
3661 current_hint_state->parent_scan_hint = NULL;
3662 current_hint_state->parent_parallel_hint = NULL;
3665 if (new_parent_relid > 0)
3668 * Here we found a new parent for the current relation. Scan continues
3669 * hint to other childrens of this parent so remember it to avoid
3670 * redundant setup cost.
3672 current_hint_state->parent_relid = new_parent_relid;
3674 /* Find hints for the parent */
3675 current_hint_state->parent_scan_hint =
3676 find_scan_hint(root, current_hint_state->parent_relid);
3678 current_hint_state->parent_parallel_hint =
3679 find_parallel_hint(root, current_hint_state->parent_relid);
3682 * If hint is found for the parent, apply it for this child instead
3685 if (current_hint_state->parent_scan_hint)
3687 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3689 pshint->base.state = HINT_STATE_USED;
3691 /* Apply index mask in the same manner to the parent. */
3692 if (pshint->indexnames)
3695 Relation parent_rel;
3698 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3699 parent_rel = heap_open(parentrel_oid, NoLock);
3701 /* Search the parent relation for indexes match the hint spec */
3702 foreach(l, RelationGetIndexList(parent_rel))
3704 Oid indexoid = lfirst_oid(l);
3705 char *indexname = get_rel_name(indexoid);
3707 ParentIndexInfo *parent_index_info;
3709 foreach(lc, pshint->indexnames)
3711 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3718 get_parent_index_info(indexoid, parentrel_oid);
3719 current_hint_state->parent_index_infos =
3720 lappend(current_hint_state->parent_index_infos,
3723 heap_close(parent_rel, NoLock);
3728 shint = find_scan_hint(root, rel->relid);
3730 shint = current_hint_state->parent_scan_hint;
3734 bool using_parent_hint =
3735 (shint == current_hint_state->parent_scan_hint);
3737 ret |= HINT_BM_SCAN_METHOD;
3739 /* Setup scan enforcement environment */
3740 setup_scan_method_enforcement(shint, current_hint_state);
3742 /* restrict unwanted inexes */
3743 restrict_indexes(root, shint, rel, using_parent_hint);
3745 if (debug_level > 1)
3747 char *additional_message = "";
3749 if (shint == current_hint_state->parent_scan_hint)
3750 additional_message = " by parent hint";
3752 ereport(pg_hint_plan_message_level,
3754 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3755 " index deletion%s:"
3756 " relation=%u(%s), inhparent=%d, "
3757 "current_hint_state=%p,"
3758 " hint_inhibit_level=%d, scanmask=0x%x",
3759 qnostr, additional_message,
3761 get_rel_name(relationObjectId),
3762 inhparent, current_hint_state,
3764 shint->enforce_mask)));
3768 /* Do the same for parallel plan enforcement */
3769 phint = find_parallel_hint(root, rel->relid);
3771 phint = current_hint_state->parent_parallel_hint;
3773 setup_parallel_plan_enforcement(phint, current_hint_state);
3776 ret |= HINT_BM_PARALLEL;
3778 /* Nothing to apply. Reset the scan mask to intial state */
3779 if (!shint && ! phint)
3781 if (debug_level > 1)
3782 ereport(pg_hint_plan_message_level,
3783 (errhidestmt (true),
3784 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3786 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3787 " hint_inhibit_level=%d, scanmask=0x%x",
3788 qnostr, relationObjectId,
3789 get_rel_name(relationObjectId),
3790 inhparent, current_hint_state, hint_inhibit_level,
3791 current_hint_state->init_scan_mask)));
3793 setup_scan_method_enforcement(NULL, current_hint_state);
3798 if (rshint != NULL) *rshint = shint;
3799 if (rphint != NULL) *rphint = phint;
3805 * Return index of relation which matches given aliasname, or 0 if not found.
3806 * If same aliasname was used multiple times in a query, return -1.
3809 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3815 for (i = 1; i < root->simple_rel_array_size; i++)
3819 if (root->simple_rel_array[i] == NULL)
3822 Assert(i == root->simple_rel_array[i]->relid);
3824 if (RelnameCmp(&aliasname,
3825 &root->simple_rte_array[i]->eref->aliasname) != 0)
3828 foreach(l, initial_rels)
3830 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3832 if (rel->reloptkind == RELOPT_BASEREL)
3834 if (rel->relid != i)
3839 Assert(rel->reloptkind == RELOPT_JOINREL);
3841 if (!bms_is_member(i, rel->relids))
3848 ("Relation name \"%s\" is ambiguous.",
3863 * Return join hint which matches given joinrelids.
3865 static JoinMethodHint *
3866 find_join_hint(Relids joinrelids)
3871 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3873 foreach(l, join_hint)
3875 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3877 if (bms_equal(joinrelids, hint->joinrelids))
3885 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3886 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3888 OuterInnerRels *outer_rels;
3889 OuterInnerRels *inner_rels;
3890 Relids outer_relids;
3891 Relids inner_relids;
3893 JoinMethodHint *hint;
3895 if (outer_inner->relation != NULL)
3897 return bms_make_singleton(
3898 find_relid_aliasname(root, outer_inner->relation,
3900 leading_hint->base.hint_str));
3903 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3904 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3906 outer_relids = OuterInnerJoinCreate(outer_rels,
3912 inner_relids = OuterInnerJoinCreate(inner_rels,
3919 join_relids = bms_add_members(outer_relids, inner_relids);
3921 if (bms_num_members(join_relids) > nbaserel)
3925 * If we don't have join method hint, create new one for the
3926 * join combination with all join methods are enabled.
3928 hint = find_join_hint(join_relids);
3932 * Here relnames is not set, since Relids bitmap is sufficient to
3933 * control paths of this query afterward.
3935 hint = (JoinMethodHint *) JoinMethodHintCreate(
3936 leading_hint->base.hint_str,
3938 HINT_KEYWORD_LEADING);
3939 hint->base.state = HINT_STATE_USED;
3940 hint->nrels = bms_num_members(join_relids);
3941 hint->enforce_mask = ENABLE_ALL_JOIN;
3942 hint->joinrelids = bms_copy(join_relids);
3943 hint->inner_nrels = bms_num_members(inner_relids);
3944 hint->inner_joinrelids = bms_copy(inner_relids);
3946 hstate->join_hint_level[hint->nrels] =
3947 lappend(hstate->join_hint_level[hint->nrels], hint);
3951 hint->inner_nrels = bms_num_members(inner_relids);
3952 hint->inner_joinrelids = bms_copy(inner_relids);
3959 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3960 int nrels, char **relnames)
3963 Relids relids = NULL;
3967 for (j = 0; j < nrels; j++)
3969 relname = relnames[j];
3971 relid = find_relid_aliasname(root, relname, initial_rels,
3975 base->state = HINT_STATE_ERROR;
3978 * the aliasname is not found(relid == 0) or same aliasname was used
3979 * multiple times in a query(relid == -1)
3986 if (bms_is_member(relid, relids))
3988 hint_ereport(base->hint_str,
3989 ("Relation name \"%s\" is duplicated.", relname));
3990 base->state = HINT_STATE_ERROR;
3994 relids = bms_add_member(relids, relid);
3999 * Transform join method hint into handy form.
4001 * - create bitmap of relids from alias names, to make it easier to check
4002 * whether a join path matches a join method hint.
4003 * - add join method hints which are necessary to enforce join order
4004 * specified by Leading hint
4007 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
4008 List *initial_rels, JoinMethodHint **join_method_hints)
4016 LeadingHint *lhint = NULL;
4019 * Create bitmap of relids from alias names for each join method hint.
4020 * Bitmaps are more handy than strings in join searching.
4022 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
4024 JoinMethodHint *hint = hstate->join_hints[i];
4026 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4029 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4030 initial_rels, hint->nrels, hint->relnames);
4032 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
4035 hstate->join_hint_level[hint->nrels] =
4036 lappend(hstate->join_hint_level[hint->nrels], hint);
4040 * Create bitmap of relids from alias names for each rows hint.
4041 * Bitmaps are more handy than strings in join searching.
4043 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
4045 RowsHint *hint = hstate->rows_hints[i];
4047 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
4050 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
4051 initial_rels, hint->nrels, hint->relnames);
4054 /* Do nothing if no Leading hint was supplied. */
4055 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
4059 * Decide whether to use Leading hint
4061 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
4063 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
4066 if (leading_hint->base.state == HINT_STATE_ERROR)
4072 foreach(l, leading_hint->relations)
4074 relname = (char *)lfirst(l);;
4076 relid = find_relid_aliasname(root, relname, initial_rels,
4077 leading_hint->base.hint_str);
4079 leading_hint->base.state = HINT_STATE_ERROR;
4084 if (bms_is_member(relid, relids))
4086 hint_ereport(leading_hint->base.hint_str,
4087 ("Relation name \"%s\" is duplicated.", relname));
4088 leading_hint->base.state = HINT_STATE_ERROR;
4092 relids = bms_add_member(relids, relid);
4095 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4100 hint_ereport(lhint->base.hint_str,
4101 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4102 lhint->base.state = HINT_STATE_DUPLICATION;
4104 leading_hint->base.state = HINT_STATE_USED;
4105 lhint = leading_hint;
4108 /* check to exist Leading hint marked with 'used'. */
4113 * We need join method hints which fit specified join order in every join
4114 * level. For example, Leading(A B C) virtually requires following join
4115 * method hints, if no join method hint supplied:
4117 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4118 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4120 * If we already have join method hint which fits specified join order in
4121 * that join level, we leave it as-is and don't add new hints.
4125 if (lhint->outer_inner == NULL)
4127 foreach(l, lhint->relations)
4129 JoinMethodHint *hint;
4131 relname = (char *)lfirst(l);
4134 * Find relid of the relation which has given name. If we have the
4135 * name given in Leading hint multiple times in the join, nothing to
4138 relid = find_relid_aliasname(root, relname, initial_rels,
4141 /* Create bitmap of relids for current join level. */
4142 joinrelids = bms_add_member(joinrelids, relid);
4145 /* We never have join method hint for single relation. */
4150 * If we don't have join method hint, create new one for the
4151 * join combination with all join methods are enabled.
4153 hint = find_join_hint(joinrelids);
4157 * Here relnames is not set, since Relids bitmap is sufficient
4158 * to control paths of this query afterward.
4160 hint = (JoinMethodHint *) JoinMethodHintCreate(
4161 lhint->base.hint_str,
4163 HINT_KEYWORD_LEADING);
4164 hint->base.state = HINT_STATE_USED;
4165 hint->nrels = njoinrels;
4166 hint->enforce_mask = ENABLE_ALL_JOIN;
4167 hint->joinrelids = bms_copy(joinrelids);
4170 join_method_hints[njoinrels] = hint;
4172 if (njoinrels >= nbaserel)
4175 bms_free(joinrelids);
4181 * Delete all join hints which have different combination from Leading
4184 for (i = 2; i <= njoinrels; i++)
4186 list_free(hstate->join_hint_level[i]);
4188 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4193 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4200 njoinrels = bms_num_members(joinrelids);
4201 Assert(njoinrels >= 2);
4204 * Delete all join hints which have different combination from Leading
4207 for (i = 2;i <= njoinrels; i++)
4209 if (hstate->join_hint_level[i] != NIL)
4211 ListCell *prev = NULL;
4212 ListCell *next = NULL;
4213 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4216 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4220 if (hint->inner_nrels == 0 &&
4221 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4222 bms_equal(bms_union(hint->joinrelids, joinrelids),
4225 hstate->join_hint_level[i] =
4226 list_delete_cell(hstate->join_hint_level[i], l,
4235 bms_free(joinrelids);
4238 if (hint_state_enabled(lhint))
4240 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4247 * wrapper of make_join_rel()
4249 * call make_join_rel() after changing enable_* parameters according to given
4253 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4256 JoinMethodHint *hint;
4260 joinrelids = bms_union(rel1->relids, rel2->relids);
4261 hint = find_join_hint(joinrelids);
4262 bms_free(joinrelids);
4265 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4267 if (hint->inner_nrels == 0)
4269 save_nestlevel = NewGUCNestLevel();
4271 set_join_config_options(hint->enforce_mask,
4272 current_hint_state->context);
4274 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4275 hint->base.state = HINT_STATE_USED;
4278 * Restore the GUC variables we set above.
4280 AtEOXact_GUC(true, save_nestlevel);
4283 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4292 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4293 RelOptInfo *joinrel,
4294 RelOptInfo *outerrel,
4295 RelOptInfo *innerrel,
4297 SpecialJoinInfo *sjinfo,
4301 JoinMethodHint *join_hint;
4304 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4305 join_hint = find_join_hint(joinrelids);
4306 bms_free(joinrelids);
4308 if (join_hint && join_hint->inner_nrels != 0)
4310 save_nestlevel = NewGUCNestLevel();
4312 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4315 set_join_config_options(join_hint->enforce_mask,
4316 current_hint_state->context);
4318 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4319 sjinfo, restrictlist);
4320 join_hint->base.state = HINT_STATE_USED;
4324 set_join_config_options(DISABLE_ALL_JOIN,
4325 current_hint_state->context);
4326 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4327 sjinfo, restrictlist);
4331 * Restore the GUC variables we set above.
4333 AtEOXact_GUC(true, save_nestlevel);
4336 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4337 sjinfo, restrictlist);
4341 get_num_baserels(List *initial_rels)
4346 foreach(l, initial_rels)
4348 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4350 if (rel->reloptkind == RELOPT_BASEREL)
4352 else if (rel->reloptkind ==RELOPT_JOINREL)
4353 nbaserel+= bms_num_members(rel->relids);
4356 /* other values not expected here */
4357 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4365 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4368 JoinMethodHint **join_method_hints;
4372 bool leading_hint_enable;
4375 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4376 * valid hint is supplied or current nesting depth is nesting depth of SPI
4379 if (!current_hint_state || hint_inhibit_level > 0)
4381 if (prev_join_search)
4382 return (*prev_join_search) (root, levels_needed, initial_rels);
4383 else if (enable_geqo && levels_needed >= geqo_threshold)
4384 return geqo(root, levels_needed, initial_rels);
4386 return standard_join_search(root, levels_needed, initial_rels);
4390 * In the case using GEQO, only scan method hints and Set hints have
4391 * effect. Join method and join order is not controllable by hints.
4393 if (enable_geqo && levels_needed >= geqo_threshold)
4394 return geqo(root, levels_needed, initial_rels);
4396 nbaserel = get_num_baserels(initial_rels);
4397 current_hint_state->join_hint_level =
4398 palloc0(sizeof(List *) * (nbaserel + 1));
4399 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4401 leading_hint_enable = transform_join_hints(current_hint_state,
4403 initial_rels, join_method_hints);
4405 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4408 * Adjust number of parallel workers of the result rel to the largest
4409 * number of the component paths.
4411 if (current_hint_state->num_hints[HINT_TYPE_PARALLEL] > 0)
4416 foreach (lc, initial_rels)
4419 RelOptInfo *rel = (RelOptInfo *) lfirst(lc);
4421 foreach (lcp, rel->partial_pathlist)
4423 Path *path = (Path *) lfirst(lcp);
4425 if (nworkers < path-> parallel_workers)
4426 nworkers = path-> parallel_workers;
4430 foreach (lc, rel->partial_pathlist)
4432 Path *path = (Path *) lfirst(lc);
4434 if (path->parallel_safe && path->parallel_workers < nworkers)
4435 path->parallel_workers = nworkers;
4439 for (i = 2; i <= nbaserel; i++)
4441 list_free(current_hint_state->join_hint_level[i]);
4443 /* free Leading hint only */
4444 if (join_method_hints[i] != NULL &&
4445 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4446 JoinMethodHintDelete(join_method_hints[i]);
4448 pfree(current_hint_state->join_hint_level);
4449 pfree(join_method_hints);
4451 if (leading_hint_enable)
4452 set_join_config_options(current_hint_state->init_join_mask,
4453 current_hint_state->context);
4459 * Force number of wokers if instructed by hint
4462 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4463 Index rti, RangeTblEntry *rte)
4465 ParallelHint *phint;
4469 /* call the previous hook */
4470 if (prev_set_rel_pathlist)
4471 prev_set_rel_pathlist(root, rel, rti, rte);
4473 /* Nothing to do if no hint available */
4474 if (current_hint_state == NULL)
4477 /* Don't touch dummy rels. */
4478 if (IS_DUMMY_REL(rel))
4482 * We can accept only plain relations, foreign tables and table saples are
4483 * also unacceptable. See set_rel_pathlist.
4485 if ((rel->rtekind != RTE_RELATION &&
4486 rel->rtekind != RTE_SUBQUERY)||
4487 rte->relkind == RELKIND_FOREIGN_TABLE ||
4488 rte->tablesample != NULL)
4492 * Even though UNION ALL node doesn't have particular name so usually it is
4493 * unhintable, turn on parallel when it contains parallel nodes.
4495 if (rel->rtekind == RTE_SUBQUERY)
4498 bool inhibit_nonparallel = false;
4500 if (rel->partial_pathlist == NIL)
4503 foreach(lc, rel->partial_pathlist)
4506 AppendPath *apath = (AppendPath *) lfirst(lc);
4507 int parallel_workers = 0;
4509 if (!IsA(apath, AppendPath))
4512 foreach (lcp, apath->subpaths)
4514 Path *spath = (Path *) lfirst(lcp);
4516 if (spath->parallel_aware &&
4517 parallel_workers < spath->parallel_workers)
4518 parallel_workers = spath->parallel_workers;
4521 apath->path.parallel_workers = parallel_workers;
4522 inhibit_nonparallel = true;
4525 if (inhibit_nonparallel)
4529 foreach(lc, rel->pathlist)
4531 Path *path = (Path *) lfirst(lc);
4533 if (path->startup_cost < disable_cost)
4535 path->startup_cost += disable_cost;
4536 path->total_cost += disable_cost;
4544 /* We cannot handle if this requires an outer */
4545 if (rel->lateral_relids)
4548 /* Return if this relation gets no enfocement */
4549 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4552 /* Here, we regenerate paths with the current hint restriction */
4553 if (found_hints & HINT_BM_SCAN_METHOD || found_hints & HINT_BM_PARALLEL)
4556 * When hint is specified on non-parent relations, discard existing
4557 * paths and regenerate based on the hint considered. Otherwise we
4558 * already have hinted childx paths then just adjust the number of
4559 * planned number of workers.
4561 if (root->simple_rte_array[rel->relid]->inh)
4563 /* enforce number of workers if requested */
4564 if (phint && phint->force_parallel)
4566 if (phint->nworkers == 0)
4568 list_free_deep(rel->partial_pathlist);
4569 rel->partial_pathlist = NIL;
4573 /* prioritize partial paths */
4574 foreach (l, rel->partial_pathlist)
4576 Path *ppath = (Path *) lfirst(l);
4578 if (ppath->parallel_safe)
4580 ppath->parallel_workers = phint->nworkers;
4581 ppath->startup_cost = 0;
4582 ppath->total_cost = 0;
4586 /* disable non-partial paths */
4587 foreach (l, rel->pathlist)
4589 Path *ppath = (Path *) lfirst(l);
4591 if (ppath->startup_cost < disable_cost)
4593 ppath->startup_cost += disable_cost;
4594 ppath->total_cost += disable_cost;
4602 /* Just discard all the paths considered so far */
4603 list_free_deep(rel->pathlist);
4604 rel->pathlist = NIL;
4605 list_free_deep(rel->partial_pathlist);
4606 rel->partial_pathlist = NIL;
4608 /* Regenerate paths with the current enforcement */
4609 set_plain_rel_pathlist(root, rel, rte);
4611 /* Additional work to enforce parallel query execution */
4612 if (phint && phint->nworkers > 0)
4615 * For Parallel Append to be planned properly, we shouldn't set
4616 * the costs of non-partial paths to disable-value. Lower the
4617 * priority of non-parallel paths by setting partial path costs
4620 foreach (l, rel->partial_pathlist)
4622 Path *path = (Path *) lfirst(l);
4624 path->startup_cost = 0;
4625 path->total_cost = 0;
4628 /* enforce number of workers if requested */
4629 if (phint->force_parallel)
4631 foreach (l, rel->partial_pathlist)
4633 Path *ppath = (Path *) lfirst(l);
4635 if (ppath->parallel_safe)
4636 ppath->parallel_workers = phint->nworkers;
4640 /* Generate gather paths */
4641 if (rel->reloptkind == RELOPT_BASEREL)
4642 generate_gather_paths(root, rel, false);
4647 reset_hint_enforcement();
4652 * Build access paths for a base relation
4654 * This function was copied and edited from set_rel_pathlist() in
4655 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4656 * functions not required here.
4659 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4660 Index rti, RangeTblEntry *rte)
4662 if (IS_DUMMY_REL(rel))
4664 /* We already proved the relation empty, so nothing more to do */
4668 /* It's an "append relation", process accordingly */
4669 set_append_rel_pathlist(root, rel, rti, rte);
4673 if (rel->rtekind == RTE_RELATION)
4675 if (rte->relkind == RELKIND_RELATION)
4677 if(rte->tablesample != NULL)
4678 elog(ERROR, "sampled relation is not supported");
4680 /* Plain relation */
4681 set_plain_rel_pathlist(root, rel, rte);
4684 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4687 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4691 * Allow a plugin to editorialize on the set of Paths for this base
4692 * relation. It could add new paths (such as CustomPaths) by calling
4693 * add_path(), or delete or modify paths added by the core code.
4695 if (set_rel_pathlist_hook)
4696 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4698 /* Now find the cheapest of the paths for this rel */
4703 * stmt_beg callback is called when each query in PL/pgSQL function is about
4704 * to be executed. At that timing, we save query string in the global variable
4705 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4706 * variable for the purpose, because its content is only necessary until
4707 * planner hook is called for the query, so recursive PL/pgSQL function calls
4708 * don't harm this mechanism.
4711 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4713 plpgsql_recurse_level++;
4717 * stmt_end callback is called then each query in PL/pgSQL function has
4718 * finished. At that timing, we clear plpgsql_query_string to tell planner
4719 * hook that next call is not for a query written in PL/pgSQL block.
4722 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4724 plpgsql_recurse_level--;
4727 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4732 if (phase != RESOURCE_RELEASE_AFTER_LOCKS)
4734 /* Cancel plpgsql nest level*/
4735 plpgsql_recurse_level = 0;
4738 #define standard_join_search pg_hint_plan_standard_join_search
4739 #define join_search_one_level pg_hint_plan_join_search_one_level
4740 #define make_join_rel make_join_rel_wrapper
4743 #undef make_join_rel
4744 #define make_join_rel pg_hint_plan_make_join_rel
4745 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4746 #include "make_join_rel.c"
4748 #include "pg_stat_statements.c"