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 "optimizer/clauses.h"
20 #include "optimizer/cost.h"
21 #include "optimizer/geqo.h"
22 #include "optimizer/joininfo.h"
23 #include "optimizer/pathnode.h"
24 #include "optimizer/paths.h"
25 #include "optimizer/plancat.h"
26 #include "optimizer/planner.h"
27 #include "optimizer/prep.h"
28 #include "optimizer/restrictinfo.h"
29 #include "parser/scansup.h"
30 #include "tcop/utility.h"
31 #include "utils/builtins.h"
32 #include "utils/lsyscache.h"
33 #include "utils/memutils.h"
34 #include "utils/rel.h"
35 #include "utils/syscache.h"
36 #include "utils/resowner.h"
38 #include "catalog/pg_class.h"
40 #include "executor/spi.h"
41 #include "catalog/pg_type.h"
45 /* partially copied from pg_stat_statements */
46 #include "normalize_query.h"
49 #include "access/htup_details.h"
51 #ifdef PG_MODULE_MAGIC
55 #define BLOCK_COMMENT_START "/*"
56 #define BLOCK_COMMENT_END "*/"
57 #define HINT_COMMENT_KEYWORD "+"
58 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
59 #define HINT_END BLOCK_COMMENT_END
62 #define HINT_SEQSCAN "SeqScan"
63 #define HINT_INDEXSCAN "IndexScan"
64 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
65 #define HINT_BITMAPSCAN "BitmapScan"
66 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
67 #define HINT_TIDSCAN "TidScan"
68 #define HINT_NOSEQSCAN "NoSeqScan"
69 #define HINT_NOINDEXSCAN "NoIndexScan"
70 #define HINT_NOBITMAPSCAN "NoBitmapScan"
71 #define HINT_NOTIDSCAN "NoTidScan"
72 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
73 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
74 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
75 #define HINT_PARALLEL "Parallel"
77 #define HINT_NESTLOOP "NestLoop"
78 #define HINT_MERGEJOIN "MergeJoin"
79 #define HINT_HASHJOIN "HashJoin"
80 #define HINT_NONESTLOOP "NoNestLoop"
81 #define HINT_NOMERGEJOIN "NoMergeJoin"
82 #define HINT_NOHASHJOIN "NoHashJoin"
83 #define HINT_LEADING "Leading"
84 #define HINT_SET "Set"
85 #define HINT_ROWS "Rows"
87 #define HINT_ARRAY_DEFAULT_INITSIZE 8
89 #define hint_ereport(str, detail) \
90 ereport(pg_hint_plan_message_level, \
91 (errhidestmt(hidestmt), \
92 errmsg("pg_hint_plan%s: hint syntax error at or near \"%s\"", qnostr, (str)), \
95 #define skip_space(str) \
96 while (isspace(*str)) \
101 ENABLE_SEQSCAN = 0x01,
102 ENABLE_INDEXSCAN = 0x02,
103 ENABLE_BITMAPSCAN = 0x04,
104 ENABLE_TIDSCAN = 0x08,
105 ENABLE_INDEXONLYSCAN = 0x10
110 ENABLE_NESTLOOP = 0x01,
111 ENABLE_MERGEJOIN = 0x02,
112 ENABLE_HASHJOIN = 0x04
115 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
116 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
117 ENABLE_INDEXONLYSCAN)
118 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
119 #define DISABLE_ALL_SCAN 0
120 #define DISABLE_ALL_JOIN 0
122 /* hint keyword of enum type*/
123 typedef enum HintKeyword
125 HINT_KEYWORD_SEQSCAN,
126 HINT_KEYWORD_INDEXSCAN,
127 HINT_KEYWORD_INDEXSCANREGEXP,
128 HINT_KEYWORD_BITMAPSCAN,
129 HINT_KEYWORD_BITMAPSCANREGEXP,
130 HINT_KEYWORD_TIDSCAN,
131 HINT_KEYWORD_NOSEQSCAN,
132 HINT_KEYWORD_NOINDEXSCAN,
133 HINT_KEYWORD_NOBITMAPSCAN,
134 HINT_KEYWORD_NOTIDSCAN,
135 HINT_KEYWORD_INDEXONLYSCAN,
136 HINT_KEYWORD_INDEXONLYSCANREGEXP,
137 HINT_KEYWORD_NOINDEXONLYSCAN,
139 HINT_KEYWORD_NESTLOOP,
140 HINT_KEYWORD_MERGEJOIN,
141 HINT_KEYWORD_HASHJOIN,
142 HINT_KEYWORD_NONESTLOOP,
143 HINT_KEYWORD_NOMERGEJOIN,
144 HINT_KEYWORD_NOHASHJOIN,
146 HINT_KEYWORD_LEADING,
149 HINT_KEYWORD_PARALLEL,
151 HINT_KEYWORD_UNRECOGNIZED
154 #define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
155 (kw == HINT_KEYWORD_INDEXSCAN || \
156 kw == HINT_KEYWORD_INDEXSCANREGEXP || \
157 kw == HINT_KEYWORD_INDEXONLYSCAN || \
158 kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
159 kw == HINT_KEYWORD_BITMAPSCAN || \
160 kw == HINT_KEYWORD_BITMAPSCANREGEXP)
163 typedef struct Hint Hint;
164 typedef struct HintState HintState;
166 typedef Hint *(*HintCreateFunction) (const char *hint_str,
168 HintKeyword hint_keyword);
169 typedef void (*HintDeleteFunction) (Hint *hint);
170 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
171 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
172 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
173 Query *parse, const char *str);
176 #define NUM_HINT_TYPE 6
177 typedef enum HintType
179 HINT_TYPE_SCAN_METHOD,
180 HINT_TYPE_JOIN_METHOD,
187 static const char *HintTypeName[] = {
197 typedef enum HintStatus
199 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
200 HINT_STATE_USED, /* hint is used */
201 HINT_STATE_DUPLICATION, /* specified hint duplication */
202 HINT_STATE_ERROR /* execute error (parse error does not include
206 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
207 (hint)->base.state == HINT_STATE_USED)
209 static unsigned int qno = 0;
210 static char qnostr[32];
212 /* common data for all hints. */
215 const char *hint_str; /* must not do pfree */
216 const char *keyword; /* must not do pfree */
217 HintKeyword hint_keyword;
220 HintDeleteFunction delete_func;
221 HintDescFunction desc_func;
222 HintCmpFunction cmp_func;
223 HintParseFunction parse_func;
226 /* scan method hints */
227 typedef struct ScanMethodHint
233 unsigned char enforce_mask;
236 typedef struct ParentIndexInfo
241 char *expression_str;
248 /* join method hints */
249 typedef struct JoinMethodHint
255 unsigned char enforce_mask;
257 Relids inner_joinrelids;
260 /* join order hints */
261 typedef struct OuterInnerRels
264 List *outer_inner_pair;
267 typedef struct LeadingHint
270 List *relations; /* relation names specified in Leading hint */
271 OuterInnerRels *outer_inner;
274 /* change a run-time parameter hints */
275 typedef struct SetHint
278 char *name; /* name of variable */
284 typedef enum RowsValueType {
285 RVT_ABSOLUTE, /* Rows(... #1000) */
286 RVT_ADD, /* Rows(... +1000) */
287 RVT_SUB, /* Rows(... -1000) */
288 RVT_MULTI, /* Rows(... *1.2) */
290 typedef struct RowsHint
297 Relids inner_joinrelids;
299 RowsValueType value_type;
304 typedef struct ParallelHint
308 char *nworkers_str; /* original string of nworkers */
309 int nworkers; /* num of workers specified by Worker */
310 bool force_parallel; /* force parallel scan */
314 * Describes a context of hint processing.
318 char *hint_str; /* original hint string */
321 int nall_hints; /* # of valid all hints */
322 int max_all_hints; /* # of slots for all hints */
323 Hint **all_hints; /* parsed all hints */
325 /* # of each hints */
326 int num_hints[NUM_HINT_TYPE];
328 /* for scan method hints */
329 ScanMethodHint **scan_hints; /* parsed scan hints */
331 /* Initial values of parameters */
332 int init_scan_mask; /* enable_* mask */
333 int init_nworkers; /* max_parallel_workers_per_gather */
334 int init_min_para_size; /* min_parallel_relation_size*/
335 int init_paratup_cost; /* parallel_tuple_cost */
336 int init_parasetup_cost;/* parallel_setup_cost */
338 Index parent_relid; /* inherit parent of table relid */
339 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
340 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
341 List *parent_index_infos; /* list of parent table's index */
343 JoinMethodHint **join_hints; /* parsed join hints */
344 int init_join_mask; /* initial value join parameter */
345 List **join_hint_level;
346 LeadingHint **leading_hint; /* parsed Leading hints */
347 SetHint **set_hints; /* parsed Set hints */
348 GucContext context; /* which GUC parameters can we set? */
349 RowsHint **rows_hints; /* parsed Rows hints */
350 ParallelHint **parallel_hints; /* parsed Parallel hints */
354 * Describes a hint parser module which is bound with particular hint keyword.
356 typedef struct HintParser
359 HintCreateFunction create_func;
360 HintKeyword hint_keyword;
363 /* Module callbacks */
367 static void push_hint(HintState *hstate);
368 static void pop_hint(void);
370 static void pg_hint_plan_ProcessUtility(Node *parsetree,
371 const char *queryString,
372 ProcessUtilityContext context,
373 ParamListInfo params,
374 DestReceiver *dest, char *completionTag);
375 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
376 ParamListInfo boundParams);
377 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
378 Oid relationObjectId,
379 bool inhparent, RelOptInfo *rel);
380 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
384 /* Scan method hint callbacks */
385 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
386 HintKeyword hint_keyword);
387 static void ScanMethodHintDelete(ScanMethodHint *hint);
388 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
389 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
390 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
391 Query *parse, const char *str);
393 /* Join method hint callbacks */
394 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
395 HintKeyword hint_keyword);
396 static void JoinMethodHintDelete(JoinMethodHint *hint);
397 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
398 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
399 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
400 Query *parse, const char *str);
402 /* Leading hint callbacks */
403 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
404 HintKeyword hint_keyword);
405 static void LeadingHintDelete(LeadingHint *hint);
406 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
407 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
408 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
409 Query *parse, const char *str);
411 /* Set hint callbacks */
412 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
413 HintKeyword hint_keyword);
414 static void SetHintDelete(SetHint *hint);
415 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
416 static int SetHintCmp(const SetHint *a, const SetHint *b);
417 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
420 /* Rows hint callbacks */
421 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
422 HintKeyword hint_keyword);
423 static void RowsHintDelete(RowsHint *hint);
424 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
425 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
426 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
427 Query *parse, const char *str);
429 /* Parallel hint callbacks */
430 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
431 HintKeyword hint_keyword);
432 static void ParallelHintDelete(ParallelHint *hint);
433 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
434 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
435 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
436 Query *parse, const char *str);
438 static void quote_value(StringInfo buf, const char *value);
440 static const char *parse_quoted_value(const char *str, char **word,
443 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
446 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
447 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
448 Index rti, RangeTblEntry *rte);
449 static void create_plain_partial_paths(PlannerInfo *root,
451 static int compute_parallel_worker(RelOptInfo *rel, BlockNumber pages);
453 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
454 ListCell *other_rels);
455 static void make_rels_by_clauseless_joins(PlannerInfo *root,
457 ListCell *other_rels);
458 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
459 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
460 Index rti, RangeTblEntry *rte);
461 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
462 List *live_childrels,
463 List *all_child_pathkeys);
464 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
466 Relids required_outer);
467 static List *accumulate_append_subpath(List *subpaths, Path *path);
468 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
471 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
473 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
475 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
479 static int set_config_option_noerror(const char *name, const char *value,
480 GucContext context, GucSource source,
481 GucAction action, bool changeVal, int elevel);
482 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
484 static int set_config_int32_option(const char *name, int32 value,
488 static bool pg_hint_plan_enable_hint = true;
489 static int debug_level = 0;
490 static int pg_hint_plan_message_level = INFO;
491 /* Default is off, to keep backward compatibility. */
492 static bool pg_hint_plan_enable_hint_table = false;
494 /* Internal static variables. */
495 static bool hidestmt = false; /* Allow or inhibit STATEMENT: output */
497 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
498 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
499 /* (This could not be above 1) */
500 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
502 static const struct config_enum_entry parse_messages_level_options[] = {
503 {"debug", DEBUG2, true},
504 {"debug5", DEBUG5, false},
505 {"debug4", DEBUG4, false},
506 {"debug3", DEBUG3, false},
507 {"debug2", DEBUG2, false},
508 {"debug1", DEBUG1, false},
510 {"info", INFO, false},
511 {"notice", NOTICE, false},
512 {"warning", WARNING, false},
513 {"error", ERROR, false},
515 * {"fatal", FATAL, true},
516 * {"panic", PANIC, true},
521 static const struct config_enum_entry parse_debug_level_options[] = {
524 {"detailed", 2, false},
525 {"verbose", 3, false},
537 /* Saved hook values in case of unload */
538 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
539 static planner_hook_type prev_planner = NULL;
540 static get_relation_info_hook_type prev_get_relation_info = NULL;
541 static join_search_hook_type prev_join_search = NULL;
542 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
544 /* Hold reference to currently active hint */
545 static HintState *current_hint_state = NULL;
548 * List of hint contexts. We treat the head of the list as the Top of the
549 * context stack, so current_hint_state always points the first element of this
552 static List *HintStateStack = NIL;
555 * Holds statement name during executing EXECUTE command. NULL for other
558 static char *stmt_name = NULL;
560 static const HintParser parsers[] = {
561 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
562 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
563 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
564 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
565 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
566 HINT_KEYWORD_BITMAPSCANREGEXP},
567 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
568 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
569 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
570 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
571 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
572 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
573 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
574 HINT_KEYWORD_INDEXONLYSCANREGEXP},
575 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
577 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
578 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
579 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
580 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
581 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
582 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
584 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
585 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
586 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
587 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
589 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
592 PLpgSQL_plugin plugin_funcs = {
596 pg_hint_plan_plpgsql_stmt_beg,
597 pg_hint_plan_plpgsql_stmt_end,
603 * Module load callbacks
608 PLpgSQL_plugin **var_ptr;
610 /* Define custom GUC variables. */
611 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
612 "Force planner to use plans specified in the hint comment preceding to the query.",
614 &pg_hint_plan_enable_hint,
622 DefineCustomEnumVariable("pg_hint_plan.debug_print",
623 "Logs results of hint parsing.",
627 parse_debug_level_options,
634 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
635 "Message level of parse errors.",
637 &pg_hint_plan_message_level,
639 parse_messages_level_options,
646 DefineCustomEnumVariable("pg_hint_plan.message_level",
647 "Message level of debug messages.",
649 &pg_hint_plan_message_level,
651 parse_messages_level_options,
658 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
659 "Let pg_hint_plan look up the hint table.",
661 &pg_hint_plan_enable_hint_table,
670 prev_ProcessUtility = ProcessUtility_hook;
671 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
672 prev_planner = planner_hook;
673 planner_hook = pg_hint_plan_planner;
674 prev_get_relation_info = get_relation_info_hook;
675 get_relation_info_hook = pg_hint_plan_get_relation_info;
676 prev_join_search = join_search_hook;
677 join_search_hook = pg_hint_plan_join_search;
678 prev_set_rel_pathlist = set_rel_pathlist_hook;
679 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
681 /* setup PL/pgSQL plugin hook */
682 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
683 *var_ptr = &plugin_funcs;
685 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
689 * Module unload callback
695 PLpgSQL_plugin **var_ptr;
697 /* Uninstall hooks. */
698 ProcessUtility_hook = prev_ProcessUtility;
699 planner_hook = prev_planner;
700 get_relation_info_hook = prev_get_relation_info;
701 join_search_hook = prev_join_search;
702 set_rel_pathlist_hook = prev_set_rel_pathlist;
704 /* uninstall PL/pgSQL plugin hook */
705 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
710 * create and delete functions the hint object
714 ScanMethodHintCreate(const char *hint_str, const char *keyword,
715 HintKeyword hint_keyword)
717 ScanMethodHint *hint;
719 hint = palloc(sizeof(ScanMethodHint));
720 hint->base.hint_str = hint_str;
721 hint->base.keyword = keyword;
722 hint->base.hint_keyword = hint_keyword;
723 hint->base.type = HINT_TYPE_SCAN_METHOD;
724 hint->base.state = HINT_STATE_NOTUSED;
725 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
726 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
727 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
728 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
729 hint->relname = NULL;
730 hint->indexnames = NIL;
731 hint->regexp = false;
732 hint->enforce_mask = 0;
734 return (Hint *) hint;
738 ScanMethodHintDelete(ScanMethodHint *hint)
744 pfree(hint->relname);
745 list_free_deep(hint->indexnames);
750 JoinMethodHintCreate(const char *hint_str, const char *keyword,
751 HintKeyword hint_keyword)
753 JoinMethodHint *hint;
755 hint = palloc(sizeof(JoinMethodHint));
756 hint->base.hint_str = hint_str;
757 hint->base.keyword = keyword;
758 hint->base.hint_keyword = hint_keyword;
759 hint->base.type = HINT_TYPE_JOIN_METHOD;
760 hint->base.state = HINT_STATE_NOTUSED;
761 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
762 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
763 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
764 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
766 hint->inner_nrels = 0;
767 hint->relnames = NULL;
768 hint->enforce_mask = 0;
769 hint->joinrelids = NULL;
770 hint->inner_joinrelids = NULL;
772 return (Hint *) hint;
776 JoinMethodHintDelete(JoinMethodHint *hint)
785 for (i = 0; i < hint->nrels; i++)
786 pfree(hint->relnames[i]);
787 pfree(hint->relnames);
790 bms_free(hint->joinrelids);
791 bms_free(hint->inner_joinrelids);
796 LeadingHintCreate(const char *hint_str, const char *keyword,
797 HintKeyword hint_keyword)
801 hint = palloc(sizeof(LeadingHint));
802 hint->base.hint_str = hint_str;
803 hint->base.keyword = keyword;
804 hint->base.hint_keyword = hint_keyword;
805 hint->base.type = HINT_TYPE_LEADING;
806 hint->base.state = HINT_STATE_NOTUSED;
807 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
808 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
809 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
810 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
811 hint->relations = NIL;
812 hint->outer_inner = NULL;
814 return (Hint *) hint;
818 LeadingHintDelete(LeadingHint *hint)
823 list_free_deep(hint->relations);
824 if (hint->outer_inner)
825 pfree(hint->outer_inner);
830 SetHintCreate(const char *hint_str, const char *keyword,
831 HintKeyword hint_keyword)
835 hint = palloc(sizeof(SetHint));
836 hint->base.hint_str = hint_str;
837 hint->base.keyword = keyword;
838 hint->base.hint_keyword = hint_keyword;
839 hint->base.type = HINT_TYPE_SET;
840 hint->base.state = HINT_STATE_NOTUSED;
841 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
842 hint->base.desc_func = (HintDescFunction) SetHintDesc;
843 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
844 hint->base.parse_func = (HintParseFunction) SetHintParse;
849 return (Hint *) hint;
853 SetHintDelete(SetHint *hint)
863 list_free(hint->words);
868 RowsHintCreate(const char *hint_str, const char *keyword,
869 HintKeyword hint_keyword)
873 hint = palloc(sizeof(RowsHint));
874 hint->base.hint_str = hint_str;
875 hint->base.keyword = keyword;
876 hint->base.hint_keyword = hint_keyword;
877 hint->base.type = HINT_TYPE_ROWS;
878 hint->base.state = HINT_STATE_NOTUSED;
879 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
880 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
881 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
882 hint->base.parse_func = (HintParseFunction) RowsHintParse;
884 hint->inner_nrels = 0;
885 hint->relnames = NULL;
886 hint->joinrelids = NULL;
887 hint->inner_joinrelids = NULL;
888 hint->rows_str = NULL;
889 hint->value_type = RVT_ABSOLUTE;
892 return (Hint *) hint;
896 RowsHintDelete(RowsHint *hint)
905 for (i = 0; i < hint->nrels; i++)
906 pfree(hint->relnames[i]);
907 pfree(hint->relnames);
910 bms_free(hint->joinrelids);
911 bms_free(hint->inner_joinrelids);
916 ParallelHintCreate(const char *hint_str, const char *keyword,
917 HintKeyword hint_keyword)
921 hint = palloc(sizeof(ScanMethodHint));
922 hint->base.hint_str = hint_str;
923 hint->base.keyword = keyword;
924 hint->base.hint_keyword = hint_keyword;
925 hint->base.type = HINT_TYPE_PARALLEL;
926 hint->base.state = HINT_STATE_NOTUSED;
927 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
928 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
929 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
930 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
931 hint->relname = NULL;
933 hint->nworkers_str = "0";
935 return (Hint *) hint;
939 ParallelHintDelete(ParallelHint *hint)
945 pfree(hint->relname);
951 HintStateCreate(void)
955 hstate = palloc(sizeof(HintState));
956 hstate->hint_str = NULL;
957 hstate->nall_hints = 0;
958 hstate->max_all_hints = 0;
959 hstate->all_hints = NULL;
960 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
961 hstate->scan_hints = NULL;
962 hstate->init_scan_mask = 0;
963 hstate->init_nworkers = 0;
964 hstate->init_min_para_size = 0;
965 hstate->init_paratup_cost = 0;
966 hstate->init_parasetup_cost = 0;
967 hstate->parent_relid = 0;
968 hstate->parent_scan_hint = NULL;
969 hstate->parent_parallel_hint = NULL;
970 hstate->parent_index_infos = NIL;
971 hstate->join_hints = NULL;
972 hstate->init_join_mask = 0;
973 hstate->join_hint_level = NULL;
974 hstate->leading_hint = NULL;
975 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
976 hstate->set_hints = NULL;
977 hstate->rows_hints = NULL;
978 hstate->parallel_hints = NULL;
984 HintStateDelete(HintState *hstate)
991 if (hstate->hint_str)
992 pfree(hstate->hint_str);
994 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
995 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
996 if (hstate->all_hints)
997 pfree(hstate->all_hints);
998 if (hstate->parent_index_infos)
999 list_free(hstate->parent_index_infos);
1003 * Copy given value into buf, with quoting with '"' if necessary.
1006 quote_value(StringInfo buf, const char *value)
1008 bool need_quote = false;
1011 for (str = value; *str != '\0'; str++)
1013 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1016 appendStringInfoCharMacro(buf, '"');
1021 for (str = value; *str != '\0'; str++)
1024 appendStringInfoCharMacro(buf, '"');
1026 appendStringInfoCharMacro(buf, *str);
1030 appendStringInfoCharMacro(buf, '"');
1034 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1038 appendStringInfo(buf, "%s(", hint->base.keyword);
1039 if (hint->relname != NULL)
1041 quote_value(buf, hint->relname);
1042 foreach(l, hint->indexnames)
1044 appendStringInfoCharMacro(buf, ' ');
1045 quote_value(buf, (char *) lfirst(l));
1048 appendStringInfoString(buf, ")");
1050 appendStringInfoChar(buf, '\n');
1054 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1058 appendStringInfo(buf, "%s(", hint->base.keyword);
1059 if (hint->relnames != NULL)
1061 quote_value(buf, hint->relnames[0]);
1062 for (i = 1; i < hint->nrels; i++)
1064 appendStringInfoCharMacro(buf, ' ');
1065 quote_value(buf, hint->relnames[i]);
1068 appendStringInfoString(buf, ")");
1070 appendStringInfoChar(buf, '\n');
1074 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1076 if (outer_inner->relation == NULL)
1083 appendStringInfoCharMacro(buf, '(');
1084 foreach(l, outer_inner->outer_inner_pair)
1089 appendStringInfoCharMacro(buf, ' ');
1091 OuterInnerDesc(lfirst(l), buf);
1094 appendStringInfoCharMacro(buf, ')');
1097 quote_value(buf, outer_inner->relation);
1101 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1103 appendStringInfo(buf, "%s(", HINT_LEADING);
1104 if (hint->outer_inner == NULL)
1111 foreach(l, hint->relations)
1116 appendStringInfoCharMacro(buf, ' ');
1118 quote_value(buf, (char *) lfirst(l));
1122 OuterInnerDesc(hint->outer_inner, buf);
1124 appendStringInfoString(buf, ")");
1126 appendStringInfoChar(buf, '\n');
1130 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1132 bool is_first = true;
1135 appendStringInfo(buf, "%s(", HINT_SET);
1136 foreach(l, hint->words)
1141 appendStringInfoCharMacro(buf, ' ');
1143 quote_value(buf, (char *) lfirst(l));
1145 appendStringInfo(buf, ")");
1147 appendStringInfoChar(buf, '\n');
1151 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1155 appendStringInfo(buf, "%s(", hint->base.keyword);
1156 if (hint->relnames != NULL)
1158 quote_value(buf, hint->relnames[0]);
1159 for (i = 1; i < hint->nrels; i++)
1161 appendStringInfoCharMacro(buf, ' ');
1162 quote_value(buf, hint->relnames[i]);
1165 appendStringInfo(buf, " %s", hint->rows_str);
1166 appendStringInfoString(buf, ")");
1168 appendStringInfoChar(buf, '\n');
1172 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1174 appendStringInfo(buf, "%s(", hint->base.keyword);
1175 if (hint->relname != NULL)
1177 quote_value(buf, hint->relname);
1179 /* number of workers */
1180 appendStringInfoCharMacro(buf, ' ');
1181 quote_value(buf, hint->nworkers_str);
1182 /* application mode of num of workers */
1183 appendStringInfoCharMacro(buf, ' ');
1184 appendStringInfoString(buf,
1185 (hint->force_parallel ? "hard" : "soft"));
1187 appendStringInfoString(buf, ")");
1189 appendStringInfoChar(buf, '\n');
1193 * Append string which represents all hints in a given state to buf, with
1194 * preceding title with them.
1197 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1198 HintStatus state, bool nolf)
1202 appendStringInfo(buf, "%s:", title);
1204 appendStringInfoChar(buf, '\n');
1207 for (i = 0; i < hstate->nall_hints; i++)
1209 if (hstate->all_hints[i]->state != state)
1212 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1216 if (nolf && nshown == 0)
1217 appendStringInfoString(buf, "(none)");
1221 * Dump contents of given hstate to server log with log level LOG.
1224 HintStateDump(HintState *hstate)
1230 elog(LOG, "pg_hint_plan:\nno hint");
1234 initStringInfo(&buf);
1236 appendStringInfoString(&buf, "pg_hint_plan:\n");
1237 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1238 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1239 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1240 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1242 elog(LOG, "%s", buf.data);
1248 HintStateDump2(HintState *hstate)
1254 elog(pg_hint_plan_message_level,
1255 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1259 initStringInfo(&buf);
1260 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1261 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1262 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1263 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1264 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1265 appendStringInfoChar(&buf, '}');
1267 ereport(pg_hint_plan_message_level,
1269 errmsg("%s", buf.data)));
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 (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 bool nulls[2] = { false, false };
1724 hint_inhibit_level++;
1731 p = SPI_prepare(search_query, 2, argtypes);
1732 plan = SPI_saveplan(p);
1736 qry = cstring_to_text(client_query);
1737 app = cstring_to_text(client_application);
1738 values[0] = PointerGetDatum(qry);
1739 values[1] = PointerGetDatum(app);
1741 SPI_execute_plan(plan, values, nulls, true, 1);
1743 if (SPI_processed > 0)
1747 hints = SPI_getvalue(SPI_tuptable->vals[0],
1748 SPI_tuptable->tupdesc, 1);
1750 * Here we use SPI_palloc to ensure that hints string is valid even
1751 * after SPI_finish call. We can't use simple palloc because it
1752 * allocates memory in SPI's context and that context is deleted in
1755 buf = SPI_palloc(strlen(hints) + 1);
1762 hint_inhibit_level--;
1766 hint_inhibit_level--;
1775 * Get client-supplied query string.
1778 get_query_string(void)
1782 if (plpgsql_recurse_level > 0)
1785 * This is quite ugly but this is the only point I could find where
1786 * we can get the query string.
1788 p = (char*)error_context_stack->arg;
1792 PreparedStatement *entry;
1794 entry = FetchPreparedStatement(stmt_name, true);
1795 p = entry->plansource->query_string;
1798 p = debug_query_string;
1804 * Get hints from the head block comment in client-supplied query string.
1807 get_hints_from_comment(const char *p)
1809 const char *hint_head;
1817 /* extract query head comment. */
1818 hint_head = strstr(p, HINT_START);
1819 if (hint_head == NULL)
1821 for (;p < hint_head; p++)
1824 * Allow these characters precedes hint comment:
1826 * - alphabets which are in ASCII range
1827 * - space, tabs and new-lines
1828 * - underscores, for identifier
1829 * - commas, for SELECT clause, EXPLAIN and PREPARE
1830 * - parentheses, for EXPLAIN and PREPARE
1832 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1833 * avoid behavior which depends on locale setting.
1835 if (!(*p >= '0' && *p <= '9') &&
1836 !(*p >= 'A' && *p <= 'Z') &&
1837 !(*p >= 'a' && *p <= 'z') &&
1841 *p != '(' && *p != ')')
1845 len = strlen(HINT_START);
1850 /* find hint end keyword. */
1851 if ((tail = strstr(p, HINT_END)) == NULL)
1853 hint_ereport(head, ("Unterminated block comment."));
1857 /* We don't support nested block comments. */
1858 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1860 hint_ereport(head, ("Nested block comments are not supported."));
1864 /* Make a copy of hint. */
1866 head = palloc(len + 1);
1867 memcpy(head, p, len);
1875 * Parse hints that got, create hint struct from parse tree and parse hints.
1878 create_hintstate(Query *parse, const char *hints)
1887 /* -1 means that no Parallel hint is specified. */
1888 max_hint_nworkers = -1;
1891 hstate = HintStateCreate();
1892 hstate->hint_str = (char *) hints;
1894 /* parse each hint. */
1895 parse_hints(hstate, parse, p);
1897 /* When nothing specified a hint, we free HintState and returns NULL. */
1898 if (hstate->nall_hints == 0)
1900 HintStateDelete(hstate);
1904 /* Sort hints in order of original position. */
1905 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1908 /* Count number of hints per hint-type. */
1909 for (i = 0; i < hstate->nall_hints; i++)
1911 Hint *cur_hint = hstate->all_hints[i];
1912 hstate->num_hints[cur_hint->type]++;
1916 * If an object (or a set of objects) has multiple hints of same hint-type,
1917 * only the last hint is valid and others are ignored in planning.
1918 * Hints except the last are marked as 'duplicated' to remember the order.
1920 for (i = 0; i < hstate->nall_hints - 1; i++)
1922 Hint *cur_hint = hstate->all_hints[i];
1923 Hint *next_hint = hstate->all_hints[i + 1];
1926 * Leading hint is marked as 'duplicated' in transform_join_hints.
1928 if (cur_hint->type == HINT_TYPE_LEADING &&
1929 next_hint->type == HINT_TYPE_LEADING)
1933 * Note that we need to pass addresses of hint pointers, because
1934 * HintCmp is designed to sort array of Hint* by qsort.
1936 if (HintCmp(&cur_hint, &next_hint) == 0)
1938 hint_ereport(cur_hint->hint_str,
1939 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1940 cur_hint->state = HINT_STATE_DUPLICATION;
1945 * Make sure that per-type array pointers point proper position in the
1946 * array which consists of all hints.
1948 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1949 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1950 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1951 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1952 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1953 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1954 hstate->num_hints[HINT_TYPE_LEADING]);
1955 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1956 hstate->num_hints[HINT_TYPE_SET]);
1957 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
1958 hstate->num_hints[HINT_TYPE_ROWS]);
1964 * Parse inside of parentheses of scan-method hints.
1967 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1970 const char *keyword = hint->base.keyword;
1971 HintKeyword hint_keyword = hint->base.hint_keyword;
1972 List *name_list = NIL;
1975 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1978 /* Parse relation name and index name(s) if given hint accepts. */
1979 length = list_length(name_list);
1981 /* at least twp parameters required */
1985 ("%s hint requires a relation.", hint->base.keyword));
1986 hint->base.state = HINT_STATE_ERROR;
1990 hint->relname = linitial(name_list);
1991 hint->indexnames = list_delete_first(name_list);
1993 /* check whether the hint accepts index name(s) */
1994 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
1997 ("%s hint accepts only one relation.",
1998 hint->base.keyword));
1999 hint->base.state = HINT_STATE_ERROR;
2003 /* Set a bit for specified hint. */
2004 switch (hint_keyword)
2006 case HINT_KEYWORD_SEQSCAN:
2007 hint->enforce_mask = ENABLE_SEQSCAN;
2009 case HINT_KEYWORD_INDEXSCAN:
2010 hint->enforce_mask = ENABLE_INDEXSCAN;
2012 case HINT_KEYWORD_INDEXSCANREGEXP:
2013 hint->enforce_mask = ENABLE_INDEXSCAN;
2014 hint->regexp = true;
2016 case HINT_KEYWORD_BITMAPSCAN:
2017 hint->enforce_mask = ENABLE_BITMAPSCAN;
2019 case HINT_KEYWORD_BITMAPSCANREGEXP:
2020 hint->enforce_mask = ENABLE_BITMAPSCAN;
2021 hint->regexp = true;
2023 case HINT_KEYWORD_TIDSCAN:
2024 hint->enforce_mask = ENABLE_TIDSCAN;
2026 case HINT_KEYWORD_NOSEQSCAN:
2027 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2029 case HINT_KEYWORD_NOINDEXSCAN:
2030 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2032 case HINT_KEYWORD_NOBITMAPSCAN:
2033 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2035 case HINT_KEYWORD_NOTIDSCAN:
2036 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2038 case HINT_KEYWORD_INDEXONLYSCAN:
2039 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2041 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2042 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2043 hint->regexp = true;
2045 case HINT_KEYWORD_NOINDEXONLYSCAN:
2046 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2049 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2058 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2061 const char *keyword = hint->base.keyword;
2062 HintKeyword hint_keyword = hint->base.hint_keyword;
2063 List *name_list = NIL;
2065 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2068 hint->nrels = list_length(name_list);
2070 if (hint->nrels > 0)
2076 * Transform relation names from list to array to sort them with qsort
2079 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2080 foreach (l, name_list)
2082 hint->relnames[i] = lfirst(l);
2087 list_free(name_list);
2089 /* A join hint requires at least two relations */
2090 if (hint->nrels < 2)
2093 ("%s hint requires at least two relations.",
2094 hint->base.keyword));
2095 hint->base.state = HINT_STATE_ERROR;
2099 /* Sort hints in alphabetical order of relation names. */
2100 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2102 switch (hint_keyword)
2104 case HINT_KEYWORD_NESTLOOP:
2105 hint->enforce_mask = ENABLE_NESTLOOP;
2107 case HINT_KEYWORD_MERGEJOIN:
2108 hint->enforce_mask = ENABLE_MERGEJOIN;
2110 case HINT_KEYWORD_HASHJOIN:
2111 hint->enforce_mask = ENABLE_HASHJOIN;
2113 case HINT_KEYWORD_NONESTLOOP:
2114 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2116 case HINT_KEYWORD_NOMERGEJOIN:
2117 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2119 case HINT_KEYWORD_NOHASHJOIN:
2120 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2123 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2132 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2135 if (outer_inner->outer_inner_pair == NIL)
2137 if (outer_inner->relation)
2143 if (list_length(outer_inner->outer_inner_pair) == 2)
2145 foreach(l, outer_inner->outer_inner_pair)
2147 if (!OuterInnerPairCheck(lfirst(l)))
2158 OuterInnerList(OuterInnerRels *outer_inner)
2160 List *outer_inner_list = NIL;
2162 OuterInnerRels *outer_inner_rels;
2164 foreach(l, outer_inner->outer_inner_pair)
2166 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2168 if (outer_inner_rels->relation != NULL)
2169 outer_inner_list = lappend(outer_inner_list,
2170 outer_inner_rels->relation);
2172 outer_inner_list = list_concat(outer_inner_list,
2173 OuterInnerList(outer_inner_rels));
2175 return outer_inner_list;
2179 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2182 List *name_list = NIL;
2183 OuterInnerRels *outer_inner = NULL;
2185 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2189 if (outer_inner != NULL)
2190 name_list = OuterInnerList(outer_inner);
2192 hint->relations = name_list;
2193 hint->outer_inner = outer_inner;
2195 /* A Leading hint requires at least two relations */
2196 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2198 hint_ereport(hint->base.hint_str,
2199 ("%s hint requires at least two relations.",
2201 hint->base.state = HINT_STATE_ERROR;
2203 else if (hint->outer_inner != NULL &&
2204 !OuterInnerPairCheck(hint->outer_inner))
2206 hint_ereport(hint->base.hint_str,
2207 ("%s hint requires two sets of relations when parentheses nests.",
2209 hint->base.state = HINT_STATE_ERROR;
2216 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2218 List *name_list = NIL;
2220 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2224 hint->words = name_list;
2226 /* We need both name and value to set GUC parameter. */
2227 if (list_length(name_list) == 2)
2229 hint->name = linitial(name_list);
2230 hint->value = lsecond(name_list);
2234 hint_ereport(hint->base.hint_str,
2235 ("%s hint requires name and value of GUC parameter.",
2237 hint->base.state = HINT_STATE_ERROR;
2244 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2247 HintKeyword hint_keyword = hint->base.hint_keyword;
2248 List *name_list = NIL;
2252 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2255 /* Last element must be rows specification */
2256 hint->nrels = list_length(name_list) - 1;
2258 if (hint->nrels > 0)
2264 * Transform relation names from list to array to sort them with qsort
2267 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2268 foreach (l, name_list)
2270 if (hint->nrels <= i)
2272 hint->relnames[i] = lfirst(l);
2277 /* Retieve rows estimation */
2278 rows_str = list_nth(name_list, hint->nrels);
2279 hint->rows_str = rows_str; /* store as-is for error logging */
2280 if (rows_str[0] == '#')
2282 hint->value_type = RVT_ABSOLUTE;
2285 else if (rows_str[0] == '+')
2287 hint->value_type = RVT_ADD;
2290 else if (rows_str[0] == '-')
2292 hint->value_type = RVT_SUB;
2295 else if (rows_str[0] == '*')
2297 hint->value_type = RVT_MULTI;
2302 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2303 hint->base.state = HINT_STATE_ERROR;
2306 hint->rows = strtod(rows_str, &end_ptr);
2309 hint_ereport(rows_str,
2310 ("%s hint requires valid number as rows estimation.",
2311 hint->base.keyword));
2312 hint->base.state = HINT_STATE_ERROR;
2316 /* A join hint requires at least two relations */
2317 if (hint->nrels < 2)
2320 ("%s hint requires at least two relations.",
2321 hint->base.keyword));
2322 hint->base.state = HINT_STATE_ERROR;
2326 list_free(name_list);
2328 /* Sort relnames in alphabetical order. */
2329 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2335 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2338 HintKeyword hint_keyword = hint->base.hint_keyword;
2339 List *name_list = NIL;
2343 bool force_parallel = false;
2345 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2348 /* Parse relation name and index name(s) if given hint accepts. */
2349 length = list_length(name_list);
2351 if (length < 2 || length > 3)
2354 ("Wrong number of arguments for %s hint.",
2355 hint->base.keyword));
2356 hint->base.state = HINT_STATE_ERROR;
2360 hint->relname = linitial(name_list);
2362 /* The second parameter is number of workers */
2363 hint->nworkers_str = list_nth(name_list, 1);
2364 nworkers = strtod(hint->nworkers_str, &end_ptr);
2365 if (*end_ptr || nworkers < 0)
2367 hint_ereport(hint->nworkers_str,
2368 ("number of workers must be a positive integer: %s",
2369 hint->base.keyword));
2370 hint->base.state = HINT_STATE_ERROR;
2374 hint->nworkers = nworkers;
2376 if (nworkers > max_hint_nworkers)
2377 max_hint_nworkers = nworkers;
2379 /* optional third parameter is specified */
2382 const char *modeparam = (const char *)list_nth(name_list, 2);
2383 if (strcasecmp(modeparam, "hard") == 0)
2384 force_parallel = true;
2385 else if (strcasecmp(modeparam, "soft") != 0)
2388 ("The mode of Worker hint must be soft or hard."));
2389 hint->base.state = HINT_STATE_ERROR;
2394 hint->force_parallel = force_parallel;
2400 * set GUC parameter functions
2404 get_current_scan_mask()
2409 mask |= ENABLE_SEQSCAN;
2410 if (enable_indexscan)
2411 mask |= ENABLE_INDEXSCAN;
2412 if (enable_bitmapscan)
2413 mask |= ENABLE_BITMAPSCAN;
2415 mask |= ENABLE_TIDSCAN;
2416 if (enable_indexonlyscan)
2417 mask |= ENABLE_INDEXONLYSCAN;
2423 get_current_join_mask()
2427 if (enable_nestloop)
2428 mask |= ENABLE_NESTLOOP;
2429 if (enable_mergejoin)
2430 mask |= ENABLE_MERGEJOIN;
2431 if (enable_hashjoin)
2432 mask |= ENABLE_HASHJOIN;
2438 * Sets GUC prameters without throwing exception. Reutrns false if something
2442 set_config_option_noerror(const char *name, const char *value,
2443 GucContext context, GucSource source,
2444 GucAction action, bool changeVal, int elevel)
2447 MemoryContext ccxt = CurrentMemoryContext;
2451 result = set_config_option(name, value, context, source,
2452 action, changeVal, 0, false);
2458 /* Save error info */
2459 MemoryContextSwitchTo(ccxt);
2460 errdata = CopyErrorData();
2464 (errcode(errdata->sqlerrcode),
2465 errhidestmt(hidestmt),
2466 errmsg("%s", errdata->message),
2467 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2468 errdata->hint ? errhint("%s", errdata->hint) : 0));
2469 FreeErrorData(errdata);
2477 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2478 * if something wrong.
2481 set_config_int32_option(const char *name, int32 value, GucContext context)
2483 char buf[16]; /* enough for int32 */
2485 if (snprintf(buf, 16, "%d", value) < 0)
2487 ereport(pg_hint_plan_message_level,
2488 (errmsg ("Cannot set integer value: %d: %s",
2489 max_hint_nworkers, strerror(errno))));
2494 set_config_option_noerror(name, buf, context,
2495 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2496 pg_hint_plan_message_level);
2499 /* setup scan method enforcement according to given options */
2501 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2505 for (i = 0; i < noptions; i++)
2507 SetHint *hint = options[i];
2510 if (!hint_state_enabled(hint))
2513 result = set_config_option_noerror(hint->name, hint->value, context,
2514 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2515 pg_hint_plan_message_level);
2517 hint->base.state = HINT_STATE_USED;
2519 hint->base.state = HINT_STATE_ERROR;
2526 * Setup parallel execution environment.
2528 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2531 setup_parallel_plan_enfocement(ParallelHint *hint, HintState *state)
2534 set_config_int32_option("max_parallel_workers_per_gather",
2535 hint->nworkers, state->context);
2537 set_config_int32_option("max_parallel_workers_per_gather",
2538 state->init_nworkers, state->context);
2540 /* force means that enforce parallel as far as possible */
2541 if (hint && hint->force_parallel)
2543 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2544 set_config_int32_option("parallel_setup_cost", 0, state->context);
2545 set_config_int32_option("min_parallel_relation_size", 0,
2550 set_config_int32_option("parallel_tuple_cost",
2551 state->init_paratup_cost, state->context);
2552 set_config_int32_option("parallel_setup_cost",
2553 state->init_parasetup_cost, state->context);
2554 set_config_int32_option("min_parallel_relation_size",
2555 state->init_min_para_size, state->context);
2559 #define SET_CONFIG_OPTION(name, type_bits) \
2560 set_config_option_noerror((name), \
2561 (mask & (type_bits)) ? "true" : "false", \
2562 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2566 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2567 * GUCs to the saved state in state.
2570 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2572 unsigned char enforce_mask = state->init_scan_mask;
2573 GucContext context = state->context;
2578 enforce_mask = scanhint->enforce_mask;
2579 scanhint->base.state = HINT_STATE_USED;
2582 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2583 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2584 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2586 mask = enforce_mask;
2588 mask = enforce_mask & current_hint_state->init_scan_mask;
2590 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2591 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2592 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2593 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2594 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2598 set_join_config_options(unsigned char enforce_mask, GucContext context)
2602 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2603 enforce_mask == ENABLE_HASHJOIN)
2604 mask = enforce_mask;
2606 mask = enforce_mask & current_hint_state->init_join_mask;
2608 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2609 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2610 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2614 * pg_hint_plan hook functions
2618 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2619 ProcessUtilityContext context,
2620 ParamListInfo params,
2621 DestReceiver *dest, char *completionTag)
2626 * Use standard planner if pg_hint_plan is disabled or current nesting
2627 * depth is nesting depth of SPI calls.
2629 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2631 if (debug_level > 1)
2632 ereport(pg_hint_plan_message_level,
2633 (errmsg ("pg_hint_plan: ProcessUtility:"
2634 " pg_hint_plan.enable_hint = off")));
2635 if (prev_ProcessUtility)
2636 (*prev_ProcessUtility) (parsetree, queryString,
2638 dest, completionTag);
2640 standard_ProcessUtility(parsetree, queryString,
2642 dest, completionTag);
2647 if (IsA(node, ExplainStmt))
2650 * Draw out parse tree of actual query from Query struct of EXPLAIN
2656 stmt = (ExplainStmt *) node;
2658 Assert(IsA(stmt->query, Query));
2659 query = (Query *) stmt->query;
2661 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2662 node = query->utilityStmt;
2666 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2667 * specified to preceding PREPARE command to use it as source of hints.
2669 if (IsA(node, ExecuteStmt))
2673 stmt = (ExecuteStmt *) node;
2674 stmt_name = stmt->name;
2678 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2681 if (IsA(node, CreateTableAsStmt))
2683 CreateTableAsStmt *stmt;
2686 stmt = (CreateTableAsStmt *) node;
2687 Assert(IsA(stmt->query, Query));
2688 query = (Query *) stmt->query;
2690 if (query->commandType == CMD_UTILITY &&
2691 IsA(query->utilityStmt, ExecuteStmt))
2693 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2694 stmt_name = estmt->name;
2700 if (debug_level > 1)
2701 ereport(pg_hint_plan_message_level,
2702 (errmsg ("pg_hint_plan: ProcessUtility:"
2703 " stmt_name = \"%s\", statement=\"%s\"",
2704 stmt_name, queryString)));
2708 if (prev_ProcessUtility)
2709 (*prev_ProcessUtility) (parsetree, queryString,
2711 dest, completionTag);
2713 standard_ProcessUtility(parsetree, queryString,
2715 dest, completionTag);
2729 if (prev_ProcessUtility)
2730 (*prev_ProcessUtility) (parsetree, queryString,
2732 dest, completionTag);
2734 standard_ProcessUtility(parsetree, queryString,
2736 dest, completionTag);
2740 * Push a hint into hint stack which is implemented with List struct. Head of
2741 * list is top of stack.
2744 push_hint(HintState *hstate)
2746 /* Prepend new hint to the list means pushing to stack. */
2747 HintStateStack = lcons(hstate, HintStateStack);
2749 /* Pushed hint is the one which should be used hereafter. */
2750 current_hint_state = hstate;
2753 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2757 /* Hint stack must not be empty. */
2758 if(HintStateStack == NIL)
2759 elog(ERROR, "hint stack is empty");
2762 * Take a hint at the head from the list, and free it. Switch
2763 * current_hint_state to point new head (NULL if the list is empty).
2765 HintStateStack = list_delete_first(HintStateStack);
2766 HintStateDelete(current_hint_state);
2767 if(HintStateStack == NIL)
2768 current_hint_state = NULL;
2770 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2773 static PlannedStmt *
2774 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2776 const char *hints = NULL;
2779 pgssJumbleState jstate;
2782 PlannedStmt *result;
2788 if (debug_level > 1)
2789 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2793 * Use standard planner if pg_hint_plan is disabled or current nesting
2794 * depth is nesting depth of SPI calls. Other hook functions try to change
2795 * plan with current_hint_state if any, so set it to NULL.
2797 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2799 if (debug_level > 1)
2800 elog(pg_hint_plan_message_level,
2801 "pg_hint_plan%s: planner: enable_hint=%d,"
2802 " hint_inhibit_level=%d",
2803 qnostr, pg_hint_plan_enable_hint, hint_inhibit_level);
2806 goto standard_planner_proc;
2809 /* Create hint struct from client-supplied query string. */
2810 query = get_query_string();
2813 * Create hintstate from hint specified for the query, if any.
2815 * First we lookup hint in pg_hint.hints table by normalized query string,
2816 * unless pg_hint_plan.enable_hint_table is OFF.
2817 * This parameter provides option to avoid overhead of table lookup during
2820 * If no hint was found, then we try to get hint from special query comment.
2822 if (pg_hint_plan_enable_hint_table)
2825 * Search hint information which is stored for the query and the
2826 * application. Query string is normalized before using in condition
2827 * in order to allow fuzzy matching.
2829 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2830 * careful when supporting PostgreSQL's version up.
2832 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2833 jstate.jumble_len = 0;
2834 jstate.clocations_buf_size = 32;
2835 jstate.clocations = (pgssLocationLen *)
2836 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2837 jstate.clocations_count = 0;
2838 JumbleQuery(&jstate, parse);
2840 * generate_normalized_query() copies exact given query_len bytes, so we
2841 * add 1 byte for null-termination here. As comments on
2842 * generate_normalized_query says, generate_normalized_query doesn't
2843 * take care of null-terminate, but additional 1 byte ensures that '\0'
2844 * byte in the source buffer to be copied into norm_query.
2846 query_len = strlen(query) + 1;
2847 norm_query = generate_normalized_query(&jstate,
2850 GetDatabaseEncoding());
2851 hints = get_hints_from_table(norm_query, application_name);
2852 if (debug_level > 1)
2855 snprintf(msgstr, 1024, "hints from table: \"%s\":"
2856 " normalzed_query=\"%s\", application name =\"%s\"",
2857 hints, norm_query, application_name);
2860 ereport(pg_hint_plan_message_level,
2861 (errhidestmt(hidestmt),
2862 errmsg("pg_hint_plan%s:"
2863 " no match found in table:"
2864 " application name = \"%s\","
2865 " normalzed_query=\"%s\"",
2866 qnostr, application_name, norm_query)));
2873 hints = get_hints_from_comment(query);
2875 if (debug_level > 1)
2877 snprintf(msgstr, 1024, "hints in comment=\"%s\"",
2878 hints ? hints : "(none)");
2879 if (debug_level > 2 ||
2880 stmt_name || strcmp(query, debug_query_string))
2881 snprintf(msgstr + strlen(msgstr), 1024- strlen(msgstr),
2882 ", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2883 stmt_name, query, debug_query_string);
2887 hstate = create_hintstate(parse, hints);
2890 * Use standard planner if the statement has not valid hint. Other hook
2891 * functions try to change plan with current_hint_state if any, so set it
2895 goto standard_planner_proc;
2898 * Push new hint struct to the hint stack to disable previous hint context.
2902 /* Set scan enforcement here. */
2903 save_nestlevel = NewGUCNestLevel();
2905 /* Apply Set hints, then save it as the initial state */
2906 setup_guc_enforcement(current_hint_state->set_hints,
2907 current_hint_state->num_hints[HINT_TYPE_SET],
2908 current_hint_state->context);
2910 current_hint_state->init_scan_mask = get_current_scan_mask();
2911 current_hint_state->init_join_mask = get_current_join_mask();
2912 current_hint_state->init_min_para_size = min_parallel_relation_size;
2913 current_hint_state->init_paratup_cost = parallel_tuple_cost;
2914 current_hint_state->init_parasetup_cost = parallel_setup_cost;
2917 * max_parallel_workers_per_gather should be non-zero here if Workers hint
2920 if (max_hint_nworkers >= 0)
2922 current_hint_state->init_nworkers = 0;
2923 set_config_int32_option("max_parallel_workers_per_gather",
2924 1, current_hint_state->context);
2927 if (debug_level > 1)
2929 ereport(pg_hint_plan_message_level,
2930 (errhidestmt(hidestmt),
2931 errmsg("pg_hint_plan%s: planner: %s",
2937 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
2938 * the state when this planner started when error occurred in planner.
2943 result = (*prev_planner) (parse, cursorOptions, boundParams);
2945 result = standard_planner(parse, cursorOptions, boundParams);
2950 * Rollback changes of GUC parameters, and pop current hint context
2951 * from hint stack to rewind the state.
2953 AtEOXact_GUC(true, save_nestlevel);
2959 /* Print hint in debug mode. */
2960 if (debug_level == 1)
2961 HintStateDump(current_hint_state);
2962 else if (debug_level > 1)
2963 HintStateDump2(current_hint_state);
2966 * Rollback changes of GUC parameters, and pop current hint context from
2967 * hint stack to rewind the state.
2969 AtEOXact_GUC(true, save_nestlevel);
2974 standard_planner_proc:
2975 if (debug_level > 1)
2977 ereport(pg_hint_plan_message_level,
2978 (errhidestmt(hidestmt),
2979 errmsg("pg_hint_plan%s: planner: no valid hint (%s)",
2983 current_hint_state = NULL;
2985 return (*prev_planner) (parse, cursorOptions, boundParams);
2987 return standard_planner(parse, cursorOptions, boundParams);
2991 * Find scan method hint to be applied to the given relation
2993 static ScanMethodHint *
2994 find_scan_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
3000 * We don't apply scan method hint if the relation is:
3001 * - not a base relation
3002 * - not an ordinary relation (such as join and subquery)
3004 if (rel && (rel->reloptkind != RELOPT_BASEREL ||
3005 rel->rtekind != RTE_RELATION))
3008 rte = root->simple_rte_array[relid];
3010 /* We don't force scan method of foreign tables */
3011 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3014 /* Find scan method hint, which matches given names, from the list. */
3015 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3017 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3019 /* We ignore disabled hints. */
3020 if (!hint_state_enabled(hint))
3023 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3030 static ParallelHint *
3031 find_parallel_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
3037 * We don't apply scan method hint if the relation is:
3038 * - not a base relation and inheritance children
3039 * - not an ordinary relation (such as join and subquery)
3041 if (rel && ((rel->reloptkind != RELOPT_BASEREL &&
3042 rel->reloptkind != RELOPT_OTHER_MEMBER_REL) ||
3043 rel->rtekind != RTE_RELATION))
3046 rte = root->simple_rte_array[relid];
3048 /* We can't force scan method of foreign tables */
3049 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3052 /* Find scan method hint, which matches given names, from the list. */
3053 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3055 ParallelHint *hint = current_hint_state->parallel_hints[i];
3057 /* We ignore disabled hints. */
3058 if (!hint_state_enabled(hint))
3061 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3071 * Returns TRUE on match, FALSE on no match.
3073 * s1 --- the data to match against
3074 * s2 --- the pattern
3076 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3079 regexpeq(const char *s1, const char *s2)
3085 strcpy(name.data, s1);
3086 regexp = cstring_to_text(s2);
3088 result = DirectFunctionCall2Coll(nameregexeq,
3089 DEFAULT_COLLATION_OID,
3090 NameGetDatum(&name),
3091 PointerGetDatum(regexp));
3092 return DatumGetBool(result);
3096 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
3104 * We delete all the IndexOptInfo list and prevent you from being usable by
3107 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3108 hint->enforce_mask == ENABLE_TIDSCAN)
3110 list_free_deep(rel->indexlist);
3111 rel->indexlist = NIL;
3112 hint->base.state = HINT_STATE_USED;
3118 * When a list of indexes is not specified, we just use all indexes.
3120 if (hint->indexnames == NIL)
3124 * Leaving only an specified index, we delete it from a IndexOptInfo list
3128 if (debug_level > 0)
3129 initStringInfo(&buf);
3131 for (cell = list_head(rel->indexlist); cell; cell = next)
3133 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3134 char *indexname = get_rel_name(info->indexoid);
3136 bool use_index = false;
3140 foreach(l, hint->indexnames)
3142 char *hintname = (char *) lfirst(l);
3146 result = regexpeq(indexname, hintname);
3148 result = RelnameCmp(&indexname, &hintname) == 0;
3153 if (debug_level > 0)
3155 appendStringInfoCharMacro(&buf, ' ');
3156 quote_value(&buf, indexname);
3164 * to make the index a candidate when definition of this index is
3165 * matched with the index's definition of current_hint_state.
3167 if (OidIsValid(relationObjectId) && !use_index)
3169 foreach(l, current_hint_state->parent_index_infos)
3173 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3175 /* check to match the parameter of unique */
3176 if (p_info->indisunique != info->unique)
3179 /* check to match the parameter of index's method */
3180 if (p_info->method != info->relam)
3183 /* to check to match the indexkey's configuration */
3184 if ((list_length(p_info->column_names)) !=
3188 /* check to match the indexkey's configuration */
3189 for (i = 0; i < info->ncolumns; i++)
3191 char *c_attname = NULL;
3192 char *p_attname = NULL;
3195 list_nth(p_info->column_names, i);
3197 /* both are expressions */
3198 if (info->indexkeys[i] == 0 && !p_attname)
3201 /* one's column is expression, the other is not */
3202 if (info->indexkeys[i] == 0 || !p_attname)
3205 c_attname = get_attname(relationObjectId,
3206 info->indexkeys[i]);
3208 if (strcmp(p_attname, c_attname) != 0)
3211 if (p_info->indcollation[i] != info->indexcollations[i])
3214 if (p_info->opclass[i] != info->opcintype[i])
3217 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
3218 info->reverse_sort[i])
3221 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
3222 info->nulls_first[i])
3227 if (i != info->ncolumns)
3230 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3231 (p_info->indpred_str && (info->indpred != NIL)))
3234 * Fetch the pg_index tuple by the Oid of the index
3236 ht_idx = SearchSysCache1(INDEXRELID,
3237 ObjectIdGetDatum(info->indexoid));
3239 /* check to match the expression's parameter of index */
3240 if (p_info->expression_str &&
3241 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
3248 * to change the expression's parameter of child's
3251 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3252 Anum_pg_index_indexprs,
3255 result = DirectFunctionCall2(pg_get_expr,
3260 if (strcmp(p_info->expression_str,
3261 text_to_cstring(DatumGetTextP(result))) != 0)
3264 ReleaseSysCache(ht_idx);
3270 /* Check to match the predicate's parameter of index */
3271 if (p_info->indpred_str &&
3272 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
3279 * to change the predicate's parameter of child's
3282 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3283 Anum_pg_index_indpred,
3286 result = DirectFunctionCall2(pg_get_expr,
3291 if (strcmp(p_info->indpred_str,
3292 text_to_cstring(DatumGetTextP(result))) != 0)
3295 ReleaseSysCache(ht_idx);
3302 ReleaseSysCache(ht_idx);
3304 else if (p_info->expression_str || (info->indexprs != NIL))
3306 else if (p_info->indpred_str || (info->indpred != NIL))
3311 /* to log the candidate of index */
3312 if (debug_level > 0)
3314 appendStringInfoCharMacro(&buf, ' ');
3315 quote_value(&buf, indexname);
3323 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3330 if (debug_level == 1)
3333 StringInfoData rel_buf;
3335 if (OidIsValid(relationObjectId))
3336 relname = get_rel_name(relationObjectId);
3338 relname = hint->relname;
3340 initStringInfo(&rel_buf);
3341 quote_value(&rel_buf, relname);
3344 (errmsg("available indexes for %s(%s):%s",
3349 pfree(rel_buf.data);
3354 * Return information of index definition.
3356 static ParentIndexInfo *
3357 get_parent_index_info(Oid indexoid, Oid relid)
3359 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3360 Relation indexRelation;
3361 Form_pg_index index;
3365 indexRelation = index_open(indexoid, RowExclusiveLock);
3367 index = indexRelation->rd_index;
3369 p_info->indisunique = index->indisunique;
3370 p_info->method = indexRelation->rd_rel->relam;
3372 p_info->column_names = NIL;
3373 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3374 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3375 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3377 for (i = 0; i < index->indnatts; i++)
3379 attname = get_attname(relid, index->indkey.values[i]);
3380 p_info->column_names = lappend(p_info->column_names, attname);
3382 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3383 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3384 p_info->indoption[i] = indexRelation->rd_indoption[i];
3388 * to check to match the expression's parameter of index with child indexes
3390 p_info->expression_str = NULL;
3391 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3397 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3398 Anum_pg_index_indexprs, &isnull);
3400 result = DirectFunctionCall2(pg_get_expr,
3402 ObjectIdGetDatum(relid));
3404 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3408 * to check to match the predicate's parameter of index with child indexes
3410 p_info->indpred_str = NULL;
3411 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3417 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3418 Anum_pg_index_indpred, &isnull);
3420 result = DirectFunctionCall2(pg_get_expr,
3422 ObjectIdGetDatum(relid));
3424 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3427 index_close(indexRelation, NoLock);
3433 * Set planner guc parameters according to corresponding scan hints.
3436 setup_hint_enforcement(PlannerInfo *root, Oid relationObjectId,
3437 bool inhparent, RelOptInfo *rel)
3439 Index new_parent_relid = 0;
3441 ScanMethodHint *scanhint = NULL;
3444 * We could register the parent relation of the following children here
3445 * when inhparent == true but inheritnce planner doesn't call this function
3446 * for parents. Since we cannot distinguish who called this function we
3447 * cannot do other than always seeking the parent regardless of who called
3452 if (debug_level > 1)
3453 ereport(pg_hint_plan_message_level,
3455 errmsg ("pg_hint_plan%s: get_relation_info"
3456 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3457 " current_hint_state=%p, hint_inhibit_level=%d",
3458 qnostr, relationObjectId,
3459 get_rel_name(relationObjectId),
3460 inhparent, current_hint_state, hint_inhibit_level)));
3464 /* Find the parent for this relation other than the registered parent */
3465 foreach (l, root->append_rel_list)
3467 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3469 if (appinfo->child_relid == rel->relid)
3471 if (current_hint_state->parent_relid != appinfo->parent_relid)
3472 new_parent_relid = appinfo->parent_relid;
3479 /* This relation doesn't have a parent. Cancel current_hint_state. */
3480 current_hint_state->parent_relid = 0;
3481 current_hint_state->parent_scan_hint = NULL;
3482 current_hint_state->parent_parallel_hint = NULL;
3485 if (new_parent_relid > 0)
3488 * Here we found a new parent for the current relation. Scan continues
3489 * hint to other childrens of this parent so remember it * to avoid
3490 * hinthintredundant setup cost.
3492 ScanMethodHint *parent_scan_hint = NULL;
3493 ParallelHint *parent_parallel_hint = NULL;
3495 current_hint_state->parent_relid = new_parent_relid;
3497 /* Find hints for the parent */
3498 current_hint_state->parent_scan_hint = parent_scan_hint =
3499 find_scan_hint(root, current_hint_state->parent_relid, NULL);
3501 current_hint_state->parent_parallel_hint = parent_parallel_hint =
3502 find_parallel_hint(root, current_hint_state->parent_relid, NULL);
3504 if (parent_scan_hint)
3507 * If hint is found for the parent, apply it for this child instead
3510 parent_scan_hint->base.state = HINT_STATE_USED;
3512 /* Apply index mask in the same manner to the parent. */
3513 if (parent_scan_hint->indexnames)
3516 Relation parent_rel;
3519 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3520 parent_rel = heap_open(parentrel_oid, NoLock);
3522 /* Search the parent relation for indexes match the hint spec */
3523 foreach(l, RelationGetIndexList(parent_rel))
3525 Oid indexoid = lfirst_oid(l);
3526 char *indexname = get_rel_name(indexoid);
3528 ParentIndexInfo *parent_index_info;
3530 foreach(lc, parent_scan_hint->indexnames)
3532 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3539 get_parent_index_info(indexoid, parentrel_oid);
3540 current_hint_state->parent_index_infos =
3541 lappend(current_hint_state->parent_index_infos, parent_index_info);
3543 heap_close(parent_rel, NoLock);
3547 /* Setup planner environment */
3548 setup_scan_method_enforcement(parent_scan_hint, current_hint_state);
3549 setup_parallel_plan_enfocement(
3550 find_parallel_hint(root, rel->relid, rel), current_hint_state);
3553 /* Process index restriction hint inheritance */
3554 if (current_hint_state->parent_scan_hint != 0)
3556 delete_indexes(current_hint_state->parent_scan_hint, rel,
3559 /* Scan fixation status is the same to the parent. */
3560 if (debug_level > 1)
3561 ereport(pg_hint_plan_message_level,
3563 errmsg("pg_hint_plan%s: get_relation_info:"
3564 " index deletion by parent hint: "
3565 "relation=%u(%s), inhparent=%d, current_hint_state=%p,"
3566 " hint_inhibit_level=%d",
3567 qnostr, relationObjectId,
3568 get_rel_name(relationObjectId),
3569 inhparent, current_hint_state, hint_inhibit_level)));
3573 /* This table doesn't have a parent hint. Apply its own hint if any. */
3574 if ((scanhint = find_scan_hint(root, rel->relid, rel)) != NULL)
3576 setup_scan_method_enforcement(scanhint, current_hint_state);
3578 delete_indexes(scanhint, rel, InvalidOid);
3580 if (debug_level > 1)
3581 ereport(pg_hint_plan_message_level,
3583 errmsg ("pg_hint_plan%s: get_relation_info"
3585 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3586 " hint_inhibit_level=%d, scanmask=0x%x",
3587 qnostr, relationObjectId,
3588 get_rel_name(relationObjectId),
3589 inhparent, current_hint_state, hint_inhibit_level,
3590 scanhint->enforce_mask)));
3594 /* Do the same for parallel plan enforcement */
3595 setup_parallel_plan_enfocement(find_parallel_hint(root, rel->relid, rel),
3596 current_hint_state);
3598 /* Nothing to apply. Reset the scan mask to intial state */
3599 if (debug_level > 1)
3600 ereport(pg_hint_plan_message_level,
3601 (errhidestmt (true),
3602 errmsg ("pg_hint_plan%s: get_relation_info"
3604 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3605 " hint_inhibit_level=%d, scanmask=0x%x",
3606 qnostr, relationObjectId,
3607 get_rel_name(relationObjectId),
3608 inhparent, current_hint_state, hint_inhibit_level,
3609 current_hint_state->init_scan_mask)));
3610 setup_scan_method_enforcement(NULL, current_hint_state);
3614 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
3615 bool inhparent, RelOptInfo *rel)
3617 if (prev_get_relation_info)
3618 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
3621 * Do nothing if we don't have a valid hint in this context or current
3622 * nesting depth is at SPI calls.
3624 if (!current_hint_state || hint_inhibit_level > 0)
3626 if (debug_level > 1)
3627 ereport(pg_hint_plan_message_level,
3628 (errhidestmt (true),
3629 errmsg ("pg_hint_plan%s: get_relation_info"
3630 " no hint to apply: relation=%u(%s), inhparent=%d,"
3631 " current_hint_state=%p, hint_inhibit_level=%d",
3632 qnostr, relationObjectId,
3633 get_rel_name(relationObjectId),
3634 inhparent, current_hint_state, hint_inhibit_level)));
3638 setup_hint_enforcement(root, relationObjectId, inhparent, rel);
3644 * Return index of relation which matches given aliasname, or 0 if not found.
3645 * If same aliasname was used multiple times in a query, return -1.
3648 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3654 for (i = 1; i < root->simple_rel_array_size; i++)
3658 if (root->simple_rel_array[i] == NULL)
3661 Assert(i == root->simple_rel_array[i]->relid);
3663 if (RelnameCmp(&aliasname,
3664 &root->simple_rte_array[i]->eref->aliasname) != 0)
3667 foreach(l, initial_rels)
3669 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3671 if (rel->reloptkind == RELOPT_BASEREL)
3673 if (rel->relid != i)
3678 Assert(rel->reloptkind == RELOPT_JOINREL);
3680 if (!bms_is_member(i, rel->relids))
3687 ("Relation name \"%s\" is ambiguous.",
3702 * Return join hint which matches given joinrelids.
3704 static JoinMethodHint *
3705 find_join_hint(Relids joinrelids)
3710 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3712 foreach(l, join_hint)
3714 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3716 if (bms_equal(joinrelids, hint->joinrelids))
3724 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3725 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3727 OuterInnerRels *outer_rels;
3728 OuterInnerRels *inner_rels;
3729 Relids outer_relids;
3730 Relids inner_relids;
3732 JoinMethodHint *hint;
3734 if (outer_inner->relation != NULL)
3736 return bms_make_singleton(
3737 find_relid_aliasname(root, outer_inner->relation,
3739 leading_hint->base.hint_str));
3742 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3743 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3745 outer_relids = OuterInnerJoinCreate(outer_rels,
3751 inner_relids = OuterInnerJoinCreate(inner_rels,
3758 join_relids = bms_add_members(outer_relids, inner_relids);
3760 if (bms_num_members(join_relids) > nbaserel)
3764 * If we don't have join method hint, create new one for the
3765 * join combination with all join methods are enabled.
3767 hint = find_join_hint(join_relids);
3771 * Here relnames is not set, since Relids bitmap is sufficient to
3772 * control paths of this query afterward.
3774 hint = (JoinMethodHint *) JoinMethodHintCreate(
3775 leading_hint->base.hint_str,
3777 HINT_KEYWORD_LEADING);
3778 hint->base.state = HINT_STATE_USED;
3779 hint->nrels = bms_num_members(join_relids);
3780 hint->enforce_mask = ENABLE_ALL_JOIN;
3781 hint->joinrelids = bms_copy(join_relids);
3782 hint->inner_nrels = bms_num_members(inner_relids);
3783 hint->inner_joinrelids = bms_copy(inner_relids);
3785 hstate->join_hint_level[hint->nrels] =
3786 lappend(hstate->join_hint_level[hint->nrels], hint);
3790 hint->inner_nrels = bms_num_members(inner_relids);
3791 hint->inner_joinrelids = bms_copy(inner_relids);
3798 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3799 int nrels, char **relnames)
3802 Relids relids = NULL;
3806 for (j = 0; j < nrels; j++)
3808 relname = relnames[j];
3810 relid = find_relid_aliasname(root, relname, initial_rels,
3814 base->state = HINT_STATE_ERROR;
3817 * the aliasname is not found(relid == 0) or same aliasname was used
3818 * multiple times in a query(relid == -1)
3825 if (bms_is_member(relid, relids))
3827 hint_ereport(base->hint_str,
3828 ("Relation name \"%s\" is duplicated.", relname));
3829 base->state = HINT_STATE_ERROR;
3833 relids = bms_add_member(relids, relid);
3838 * Transform join method hint into handy form.
3840 * - create bitmap of relids from alias names, to make it easier to check
3841 * whether a join path matches a join method hint.
3842 * - add join method hints which are necessary to enforce join order
3843 * specified by Leading hint
3846 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3847 List *initial_rels, JoinMethodHint **join_method_hints)
3855 LeadingHint *lhint = NULL;
3858 * Create bitmap of relids from alias names for each join method hint.
3859 * Bitmaps are more handy than strings in join searching.
3861 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3863 JoinMethodHint *hint = hstate->join_hints[i];
3865 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3868 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3869 initial_rels, hint->nrels, hint->relnames);
3871 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3874 hstate->join_hint_level[hint->nrels] =
3875 lappend(hstate->join_hint_level[hint->nrels], hint);
3879 * Create bitmap of relids from alias names for each rows hint.
3880 * Bitmaps are more handy than strings in join searching.
3882 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3884 RowsHint *hint = hstate->rows_hints[i];
3886 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3889 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3890 initial_rels, hint->nrels, hint->relnames);
3893 /* Do nothing if no Leading hint was supplied. */
3894 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3898 * Decide whether to use Leading hint
3900 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3902 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3905 if (leading_hint->base.state == HINT_STATE_ERROR)
3911 foreach(l, leading_hint->relations)
3913 relname = (char *)lfirst(l);;
3915 relid = find_relid_aliasname(root, relname, initial_rels,
3916 leading_hint->base.hint_str);
3918 leading_hint->base.state = HINT_STATE_ERROR;
3923 if (bms_is_member(relid, relids))
3925 hint_ereport(leading_hint->base.hint_str,
3926 ("Relation name \"%s\" is duplicated.", relname));
3927 leading_hint->base.state = HINT_STATE_ERROR;
3931 relids = bms_add_member(relids, relid);
3934 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3939 hint_ereport(lhint->base.hint_str,
3940 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3941 lhint->base.state = HINT_STATE_DUPLICATION;
3943 leading_hint->base.state = HINT_STATE_USED;
3944 lhint = leading_hint;
3947 /* check to exist Leading hint marked with 'used'. */
3952 * We need join method hints which fit specified join order in every join
3953 * level. For example, Leading(A B C) virtually requires following join
3954 * method hints, if no join method hint supplied:
3956 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3957 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3959 * If we already have join method hint which fits specified join order in
3960 * that join level, we leave it as-is and don't add new hints.
3964 if (lhint->outer_inner == NULL)
3966 foreach(l, lhint->relations)
3968 JoinMethodHint *hint;
3970 relname = (char *)lfirst(l);
3973 * Find relid of the relation which has given name. If we have the
3974 * name given in Leading hint multiple times in the join, nothing to
3977 relid = find_relid_aliasname(root, relname, initial_rels,
3980 /* Create bitmap of relids for current join level. */
3981 joinrelids = bms_add_member(joinrelids, relid);
3984 /* We never have join method hint for single relation. */
3989 * If we don't have join method hint, create new one for the
3990 * join combination with all join methods are enabled.
3992 hint = find_join_hint(joinrelids);
3996 * Here relnames is not set, since Relids bitmap is sufficient
3997 * to control paths of this query afterward.
3999 hint = (JoinMethodHint *) JoinMethodHintCreate(
4000 lhint->base.hint_str,
4002 HINT_KEYWORD_LEADING);
4003 hint->base.state = HINT_STATE_USED;
4004 hint->nrels = njoinrels;
4005 hint->enforce_mask = ENABLE_ALL_JOIN;
4006 hint->joinrelids = bms_copy(joinrelids);
4009 join_method_hints[njoinrels] = hint;
4011 if (njoinrels >= nbaserel)
4014 bms_free(joinrelids);
4020 * Delete all join hints which have different combination from Leading
4023 for (i = 2; i <= njoinrels; i++)
4025 list_free(hstate->join_hint_level[i]);
4027 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4032 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4039 njoinrels = bms_num_members(joinrelids);
4040 Assert(njoinrels >= 2);
4043 * Delete all join hints which have different combination from Leading
4046 for (i = 2;i <= njoinrels; i++)
4048 if (hstate->join_hint_level[i] != NIL)
4050 ListCell *prev = NULL;
4051 ListCell *next = NULL;
4052 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4055 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4059 if (hint->inner_nrels == 0 &&
4060 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4061 bms_equal(bms_union(hint->joinrelids, joinrelids),
4064 hstate->join_hint_level[i] =
4065 list_delete_cell(hstate->join_hint_level[i], l,
4074 bms_free(joinrelids);
4077 if (hint_state_enabled(lhint))
4079 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4086 * set_plain_rel_pathlist
4087 * Build access paths for a plain relation (no subquery, no inheritance)
4089 * This function was copied and edited from set_plain_rel_pathlist() in
4090 * src/backend/optimizer/path/allpaths.c
4092 * - removed parallel stuff.
4095 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
4097 Relids required_outer;
4100 * We don't support pushing join clauses into the quals of a seqscan, but
4101 * it could still have required parameterization due to LATERAL refs in
4104 required_outer = rel->lateral_relids;
4106 /* Consider sequential scan */
4107 add_path(rel, create_seqscan_path(root, rel, required_outer, 0));
4109 /* If appropriate, consider parallel sequential scan */
4110 if (rel->consider_parallel && required_outer == NULL)
4112 ParallelHint *phint = find_parallel_hint(root, rel->relid, rel);
4114 /* Consider parallel paths only if not inhibited by hint */
4115 if (!phint || phint->nworkers > 0)
4116 create_plain_partial_paths(root, rel);
4119 * Overwirte parallel_workers if requested. partial_pathlist seems to
4120 * have up to one path but looping over all possible paths don't harm.
4122 if (phint && phint->nworkers > 0 && phint->force_parallel)
4125 foreach (l, rel->partial_pathlist)
4127 Path *ppath = (Path *) lfirst(l);
4129 Assert(ppath->parallel_workers > 0);
4130 ppath->parallel_workers = phint->nworkers;
4135 /* Consider index scans */
4136 create_index_paths(root, rel);
4138 /* Consider TID scans */
4139 create_tidscan_paths(root, rel);
4143 * Clear exiting access paths and create new ones applying hints.
4144 * This does the similar to set_rel_pathlist
4147 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
4152 foreach(l, initial_rels)
4154 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4157 /* Skip relations which we can't choose scan method. */
4158 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
4161 rte = root->simple_rte_array[rel->relid];
4163 /* We can't force scan method of foreign tables */
4164 if (rte->relkind == RELKIND_FOREIGN_TABLE)
4168 * Create scan paths with GUC parameters which are at the beginning of
4169 * planner if scan method hint is not specified, otherwise use
4170 * specified hints and mark the hint as used.
4172 setup_scan_method_enforcement(find_scan_hint(root, rel->relid, rel),
4175 /* Setup parallel environment according to the hint */
4176 setup_parallel_plan_enfocement(
4177 find_parallel_hint(root, rel->relid, rel), current_hint_state);
4179 /* remove existing partial paths from this baserel */
4180 list_free_deep(rel->partial_pathlist);
4181 rel->partial_pathlist = NIL;
4183 /* remove existing paths from this baserel */
4184 list_free_deep(rel->pathlist);
4185 rel->pathlist = NIL;
4191 /* remove partial paths from all chlidren */
4192 foreach (l, root->append_rel_list)
4194 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
4195 RelOptInfo *childrel;
4197 if (appinfo->parent_relid != rel->relid)
4200 childrel = root->simple_rel_array[appinfo->child_relid];
4201 list_free_deep(childrel->partial_pathlist);
4202 childrel->partial_pathlist = NIL;
4204 /* It's an "append relation", process accordingly */
4205 set_append_rel_pathlist(root, rel, rel->relid, rte);
4209 set_plain_rel_pathlist(root, rel, rte);
4213 * If this is a baserel, consider gathering any partial paths we may
4214 * hinthave created for it.
4216 if (rel->reloptkind == RELOPT_BASEREL)
4217 generate_gather_paths(root, rel);
4219 /* Now find the cheapest of the paths for this rel */
4224 * Restore the GUC variables we set above.
4226 setup_scan_method_enforcement(NULL, hstate);
4230 * wrapper of make_join_rel()
4232 * call make_join_rel() after changing enable_* parameters according to given
4236 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4239 JoinMethodHint *hint;
4243 joinrelids = bms_union(rel1->relids, rel2->relids);
4244 hint = find_join_hint(joinrelids);
4245 bms_free(joinrelids);
4248 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4250 if (hint->inner_nrels == 0)
4252 save_nestlevel = NewGUCNestLevel();
4254 set_join_config_options(hint->enforce_mask,
4255 current_hint_state->context);
4257 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4258 hint->base.state = HINT_STATE_USED;
4261 * Restore the GUC variables we set above.
4263 AtEOXact_GUC(true, save_nestlevel);
4266 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4275 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4276 RelOptInfo *joinrel,
4277 RelOptInfo *outerrel,
4278 RelOptInfo *innerrel,
4280 SpecialJoinInfo *sjinfo,
4283 ScanMethodHint *scan_hint = NULL;
4285 JoinMethodHint *join_hint;
4288 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
4289 setup_scan_method_enforcement(scan_hint, current_hint_state);
4291 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4292 join_hint = find_join_hint(joinrelids);
4293 bms_free(joinrelids);
4295 if (join_hint && join_hint->inner_nrels != 0)
4297 save_nestlevel = NewGUCNestLevel();
4299 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4302 set_join_config_options(join_hint->enforce_mask,
4303 current_hint_state->context);
4305 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4306 sjinfo, restrictlist);
4307 join_hint->base.state = HINT_STATE_USED;
4311 set_join_config_options(DISABLE_ALL_JOIN,
4312 current_hint_state->context);
4313 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4314 sjinfo, restrictlist);
4318 * Restore the GUC variables we set above.
4320 AtEOXact_GUC(true, save_nestlevel);
4323 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4324 sjinfo, restrictlist);
4326 /* Reset the environment if changed */
4327 if (scan_hint != NULL)
4328 setup_scan_method_enforcement(NULL, current_hint_state);
4332 get_num_baserels(List *initial_rels)
4337 foreach(l, initial_rels)
4339 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4341 if (rel->reloptkind == RELOPT_BASEREL)
4343 else if (rel->reloptkind ==RELOPT_JOINREL)
4344 nbaserel+= bms_num_members(rel->relids);
4347 /* other values not expected here */
4348 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4356 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4359 JoinMethodHint **join_method_hints;
4363 bool leading_hint_enable;
4366 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4367 * valid hint is supplied or current nesting depth is nesting depth of SPI
4370 if (!current_hint_state || hint_inhibit_level > 0)
4372 if (prev_join_search)
4373 return (*prev_join_search) (root, levels_needed, initial_rels);
4374 else if (enable_geqo && levels_needed >= geqo_threshold)
4375 return geqo(root, levels_needed, initial_rels);
4377 return standard_join_search(root, levels_needed, initial_rels);
4380 /* apply scan method hint rebuild scan path. */
4381 rebuild_scan_path(current_hint_state, root, levels_needed, initial_rels);
4384 * In the case using GEQO, only scan method hints and Set hints have
4385 * effect. Join method and join order is not controllable by hints.
4387 if (enable_geqo && levels_needed >= geqo_threshold)
4388 return geqo(root, levels_needed, initial_rels);
4390 nbaserel = get_num_baserels(initial_rels);
4391 current_hint_state->join_hint_level =
4392 palloc0(sizeof(List *) * (nbaserel + 1));
4393 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4395 leading_hint_enable = transform_join_hints(current_hint_state,
4397 initial_rels, join_method_hints);
4399 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4401 for (i = 2; i <= nbaserel; i++)
4403 list_free(current_hint_state->join_hint_level[i]);
4405 /* free Leading hint only */
4406 if (join_method_hints[i] != NULL &&
4407 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4408 JoinMethodHintDelete(join_method_hints[i]);
4410 pfree(current_hint_state->join_hint_level);
4411 pfree(join_method_hints);
4413 if (leading_hint_enable)
4414 set_join_config_options(current_hint_state->init_join_mask,
4415 current_hint_state->context);
4421 * Force number of wokers if instructed by hint
4424 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4425 Index rti, RangeTblEntry *rte)
4427 ParallelHint *phint;
4430 bool regenerate = false;
4432 /* Hint has not been parsed yet, or this is not a parallel'able relation */
4433 if (current_hint_state == NULL || rel->partial_pathlist == NIL)
4436 phint = find_parallel_hint(root, rel->relid, rel);
4438 if (phint == NULL || !phint->force_parallel)
4442 * This relation contains gather paths previously created and they prevent
4443 * adding new gahter path with same cost. Remove them.
4445 oldpathlist = rel->pathlist;
4446 rel->pathlist = NIL;
4447 foreach (l, oldpathlist)
4449 Path *path = (Path *) lfirst(l);
4451 if (IsA(path, GatherPath) &&
4452 path->parallel_workers != phint->nworkers)
4458 rel->pathlist = lappend(rel->pathlist, path);
4460 list_free(oldpathlist);
4464 foreach (l, rel->partial_pathlist)
4466 Path *ppath = (Path *) lfirst(l);
4468 if (phint && phint->nworkers > 0 && phint->force_parallel)
4470 Assert(ppath->parallel_workers > 0);
4471 ppath->parallel_workers = phint->nworkers;
4475 generate_gather_paths(root, rel);
4481 * Build access paths for a base relation
4483 * This function was copied and edited from set_rel_pathlist() in
4484 * src/backend/optimizer/path/allpaths.c
4487 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4488 Index rti, RangeTblEntry *rte)
4490 if (IS_DUMMY_REL(rel))
4492 /* We already proved the relation empty, so nothing more to do */
4496 /* It's an "append relation", process accordingly */
4497 set_append_rel_pathlist(root, rel, rti, rte);
4501 if (rel->rtekind == RTE_RELATION)
4503 if (rte->relkind == RELKIND_RELATION)
4505 if(rte->tablesample != NULL)
4506 elog(ERROR, "sampled relation is not supported");
4508 /* Plain relation */
4509 set_plain_rel_pathlist(root, rel, rte);
4512 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4515 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4519 * Allow a plugin to editorialize on the set of Paths for this base
4520 * relation. It could add new paths (such as CustomPaths) by calling
4521 * add_path(), or delete or modify paths added by the core code.
4523 if (set_rel_pathlist_hook)
4524 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4526 /* Now find the cheapest of the paths for this rel */
4531 * stmt_beg callback is called when each query in PL/pgSQL function is about
4532 * to be executed. At that timing, we save query string in the global variable
4533 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4534 * variable for the purpose, because its content is only necessary until
4535 * planner hook is called for the query, so recursive PL/pgSQL function calls
4536 * don't harm this mechanism.
4539 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4541 plpgsql_recurse_level++;
4545 * stmt_end callback is called then each query in PL/pgSQL function has
4546 * finished. At that timing, we clear plpgsql_query_string to tell planner
4547 * hook that next call is not for a query written in PL/pgSQL block.
4550 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4552 plpgsql_recurse_level--;
4555 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4560 if (phase != RESOURCE_RELEASE_AFTER_LOCKS)
4562 /* Cancel plpgsql nest level*/
4563 plpgsql_recurse_level = 0;
4566 #define standard_join_search pg_hint_plan_standard_join_search
4567 #define join_search_one_level pg_hint_plan_join_search_one_level
4568 #define make_join_rel make_join_rel_wrapper
4571 #undef make_join_rel
4572 #define make_join_rel pg_hint_plan_make_join_rel
4573 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4574 #include "make_join_rel.c"
4576 #include "pg_stat_statements.c"