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 typedef enum HintTypeBitmap
189 HINT_BM_SCAN_METHOD = 1,
193 static const char *HintTypeName[] = {
203 typedef enum HintStatus
205 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
206 HINT_STATE_USED, /* hint is used */
207 HINT_STATE_DUPLICATION, /* specified hint duplication */
208 HINT_STATE_ERROR /* execute error (parse error does not include
212 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
213 (hint)->base.state == HINT_STATE_USED)
215 static unsigned int qno = 0;
216 static char qnostr[32];
218 /* common data for all hints. */
221 const char *hint_str; /* must not do pfree */
222 const char *keyword; /* must not do pfree */
223 HintKeyword hint_keyword;
226 HintDeleteFunction delete_func;
227 HintDescFunction desc_func;
228 HintCmpFunction cmp_func;
229 HintParseFunction parse_func;
232 /* scan method hints */
233 typedef struct ScanMethodHint
239 unsigned char enforce_mask;
242 typedef struct ParentIndexInfo
247 char *expression_str;
254 /* join method hints */
255 typedef struct JoinMethodHint
261 unsigned char enforce_mask;
263 Relids inner_joinrelids;
266 /* join order hints */
267 typedef struct OuterInnerRels
270 List *outer_inner_pair;
273 typedef struct LeadingHint
276 List *relations; /* relation names specified in Leading hint */
277 OuterInnerRels *outer_inner;
280 /* change a run-time parameter hints */
281 typedef struct SetHint
284 char *name; /* name of variable */
290 typedef enum RowsValueType {
291 RVT_ABSOLUTE, /* Rows(... #1000) */
292 RVT_ADD, /* Rows(... +1000) */
293 RVT_SUB, /* Rows(... -1000) */
294 RVT_MULTI, /* Rows(... *1.2) */
296 typedef struct RowsHint
303 Relids inner_joinrelids;
305 RowsValueType value_type;
310 typedef struct ParallelHint
314 char *nworkers_str; /* original string of nworkers */
315 int nworkers; /* num of workers specified by Worker */
316 bool force_parallel; /* force parallel scan */
320 * Describes a context of hint processing.
324 char *hint_str; /* original hint string */
327 int nall_hints; /* # of valid all hints */
328 int max_all_hints; /* # of slots for all hints */
329 Hint **all_hints; /* parsed all hints */
331 /* # of each hints */
332 int num_hints[NUM_HINT_TYPE];
334 /* for scan method hints */
335 ScanMethodHint **scan_hints; /* parsed scan hints */
337 /* Initial values of parameters */
338 int init_scan_mask; /* enable_* mask */
339 int init_nworkers; /* max_parallel_workers_per_gather */
340 int init_min_para_size; /* min_parallel_relation_size*/
341 int init_paratup_cost; /* parallel_tuple_cost */
342 int init_parasetup_cost;/* parallel_setup_cost */
344 Index parent_relid; /* inherit parent of table relid */
345 ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
346 ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
347 List *parent_index_infos; /* list of parent table's index */
349 JoinMethodHint **join_hints; /* parsed join hints */
350 int init_join_mask; /* initial value join parameter */
351 List **join_hint_level;
352 LeadingHint **leading_hint; /* parsed Leading hints */
353 SetHint **set_hints; /* parsed Set hints */
354 GucContext context; /* which GUC parameters can we set? */
355 RowsHint **rows_hints; /* parsed Rows hints */
356 ParallelHint **parallel_hints; /* parsed Parallel hints */
360 * Describes a hint parser module which is bound with particular hint keyword.
362 typedef struct HintParser
365 HintCreateFunction create_func;
366 HintKeyword hint_keyword;
369 /* Module callbacks */
373 static void push_hint(HintState *hstate);
374 static void pop_hint(void);
376 static void pg_hint_plan_ProcessUtility(Node *parsetree,
377 const char *queryString,
378 ProcessUtilityContext context,
379 ParamListInfo params,
380 DestReceiver *dest, char *completionTag);
381 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
382 ParamListInfo boundParams);
383 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
387 /* Scan method hint callbacks */
388 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
389 HintKeyword hint_keyword);
390 static void ScanMethodHintDelete(ScanMethodHint *hint);
391 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
392 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
393 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
394 Query *parse, const char *str);
396 /* Join method hint callbacks */
397 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
398 HintKeyword hint_keyword);
399 static void JoinMethodHintDelete(JoinMethodHint *hint);
400 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
401 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
402 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
403 Query *parse, const char *str);
405 /* Leading hint callbacks */
406 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
407 HintKeyword hint_keyword);
408 static void LeadingHintDelete(LeadingHint *hint);
409 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
410 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
411 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
412 Query *parse, const char *str);
414 /* Set hint callbacks */
415 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
416 HintKeyword hint_keyword);
417 static void SetHintDelete(SetHint *hint);
418 static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
419 static int SetHintCmp(const SetHint *a, const SetHint *b);
420 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
423 /* Rows hint callbacks */
424 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
425 HintKeyword hint_keyword);
426 static void RowsHintDelete(RowsHint *hint);
427 static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
428 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
429 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
430 Query *parse, const char *str);
432 /* Parallel hint callbacks */
433 static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
434 HintKeyword hint_keyword);
435 static void ParallelHintDelete(ParallelHint *hint);
436 static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
437 static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
438 static const char *ParallelHintParse(ParallelHint *hint, HintState *hstate,
439 Query *parse, const char *str);
441 static void quote_value(StringInfo buf, const char *value);
443 static const char *parse_quoted_value(const char *str, char **word,
446 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
449 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
450 void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
451 Index rti, RangeTblEntry *rte);
452 static void create_plain_partial_paths(PlannerInfo *root,
454 static int compute_parallel_worker(RelOptInfo *rel, BlockNumber pages);
456 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
457 ListCell *other_rels);
458 static void make_rels_by_clauseless_joins(PlannerInfo *root,
460 ListCell *other_rels);
461 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
462 static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
464 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
465 Index rti, RangeTblEntry *rte);
466 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
467 List *live_childrels,
468 List *all_child_pathkeys);
469 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
471 Relids required_outer);
472 static List *accumulate_append_subpath(List *subpaths, Path *path);
473 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
476 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
478 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
480 static void plpgsql_query_erase_callback(ResourceReleasePhase phase,
484 static int set_config_option_noerror(const char *name, const char *value,
485 GucContext context, GucSource source,
486 GucAction action, bool changeVal, int elevel);
487 static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
489 static int set_config_int32_option(const char *name, int32 value,
493 static bool pg_hint_plan_enable_hint = true;
494 static int debug_level = 0;
495 static int pg_hint_plan_message_level = INFO;
496 /* Default is off, to keep backward compatibility. */
497 static bool pg_hint_plan_enable_hint_table = false;
499 /* Internal static variables. */
500 static bool hidestmt = false; /* Allow or inhibit STATEMENT: output */
502 static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
503 static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
504 /* (This could not be above 1) */
505 static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
507 static const struct config_enum_entry parse_messages_level_options[] = {
508 {"debug", DEBUG2, true},
509 {"debug5", DEBUG5, false},
510 {"debug4", DEBUG4, false},
511 {"debug3", DEBUG3, false},
512 {"debug2", DEBUG2, false},
513 {"debug1", DEBUG1, false},
515 {"info", INFO, false},
516 {"notice", NOTICE, false},
517 {"warning", WARNING, false},
518 {"error", ERROR, false},
520 * {"fatal", FATAL, true},
521 * {"panic", PANIC, true},
526 static const struct config_enum_entry parse_debug_level_options[] = {
529 {"detailed", 2, false},
530 {"verbose", 3, false},
542 /* Saved hook values in case of unload */
543 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
544 static planner_hook_type prev_planner = NULL;
545 static join_search_hook_type prev_join_search = NULL;
546 static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
548 /* Hold reference to currently active hint */
549 static HintState *current_hint_state = NULL;
552 * List of hint contexts. We treat the head of the list as the Top of the
553 * context stack, so current_hint_state always points the first element of this
556 static List *HintStateStack = NIL;
559 * Holds statement name during executing EXECUTE command. NULL for other
562 static char *stmt_name = NULL;
564 static const HintParser parsers[] = {
565 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
566 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
567 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
568 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
569 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
570 HINT_KEYWORD_BITMAPSCANREGEXP},
571 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
572 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
573 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
574 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
575 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
576 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
577 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
578 HINT_KEYWORD_INDEXONLYSCANREGEXP},
579 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
581 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
582 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
583 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
584 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
585 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
586 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
588 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
589 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
590 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
591 {HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
593 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
596 PLpgSQL_plugin plugin_funcs = {
600 pg_hint_plan_plpgsql_stmt_beg,
601 pg_hint_plan_plpgsql_stmt_end,
607 * Module load callbacks
612 PLpgSQL_plugin **var_ptr;
614 /* Define custom GUC variables. */
615 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
616 "Force planner to use plans specified in the hint comment preceding to the query.",
618 &pg_hint_plan_enable_hint,
626 DefineCustomEnumVariable("pg_hint_plan.debug_print",
627 "Logs results of hint parsing.",
631 parse_debug_level_options,
638 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
639 "Message level of parse errors.",
641 &pg_hint_plan_message_level,
643 parse_messages_level_options,
650 DefineCustomEnumVariable("pg_hint_plan.message_level",
651 "Message level of debug messages.",
653 &pg_hint_plan_message_level,
655 parse_messages_level_options,
662 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
663 "Let pg_hint_plan look up the hint table.",
665 &pg_hint_plan_enable_hint_table,
674 prev_ProcessUtility = ProcessUtility_hook;
675 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
676 prev_planner = planner_hook;
677 planner_hook = pg_hint_plan_planner;
678 prev_join_search = join_search_hook;
679 join_search_hook = pg_hint_plan_join_search;
680 prev_set_rel_pathlist = set_rel_pathlist_hook;
681 set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
683 /* setup PL/pgSQL plugin hook */
684 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
685 *var_ptr = &plugin_funcs;
687 RegisterResourceReleaseCallback(plpgsql_query_erase_callback, NULL);
691 * Module unload callback
697 PLpgSQL_plugin **var_ptr;
699 /* Uninstall hooks. */
700 ProcessUtility_hook = prev_ProcessUtility;
701 planner_hook = prev_planner;
702 join_search_hook = prev_join_search;
703 set_rel_pathlist_hook = prev_set_rel_pathlist;
705 /* uninstall PL/pgSQL plugin hook */
706 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
711 * create and delete functions the hint object
715 ScanMethodHintCreate(const char *hint_str, const char *keyword,
716 HintKeyword hint_keyword)
718 ScanMethodHint *hint;
720 hint = palloc(sizeof(ScanMethodHint));
721 hint->base.hint_str = hint_str;
722 hint->base.keyword = keyword;
723 hint->base.hint_keyword = hint_keyword;
724 hint->base.type = HINT_TYPE_SCAN_METHOD;
725 hint->base.state = HINT_STATE_NOTUSED;
726 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
727 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
728 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
729 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
730 hint->relname = NULL;
731 hint->indexnames = NIL;
732 hint->regexp = false;
733 hint->enforce_mask = 0;
735 return (Hint *) hint;
739 ScanMethodHintDelete(ScanMethodHint *hint)
745 pfree(hint->relname);
746 list_free_deep(hint->indexnames);
751 JoinMethodHintCreate(const char *hint_str, const char *keyword,
752 HintKeyword hint_keyword)
754 JoinMethodHint *hint;
756 hint = palloc(sizeof(JoinMethodHint));
757 hint->base.hint_str = hint_str;
758 hint->base.keyword = keyword;
759 hint->base.hint_keyword = hint_keyword;
760 hint->base.type = HINT_TYPE_JOIN_METHOD;
761 hint->base.state = HINT_STATE_NOTUSED;
762 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
763 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
764 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
765 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
767 hint->inner_nrels = 0;
768 hint->relnames = NULL;
769 hint->enforce_mask = 0;
770 hint->joinrelids = NULL;
771 hint->inner_joinrelids = NULL;
773 return (Hint *) hint;
777 JoinMethodHintDelete(JoinMethodHint *hint)
786 for (i = 0; i < hint->nrels; i++)
787 pfree(hint->relnames[i]);
788 pfree(hint->relnames);
791 bms_free(hint->joinrelids);
792 bms_free(hint->inner_joinrelids);
797 LeadingHintCreate(const char *hint_str, const char *keyword,
798 HintKeyword hint_keyword)
802 hint = palloc(sizeof(LeadingHint));
803 hint->base.hint_str = hint_str;
804 hint->base.keyword = keyword;
805 hint->base.hint_keyword = hint_keyword;
806 hint->base.type = HINT_TYPE_LEADING;
807 hint->base.state = HINT_STATE_NOTUSED;
808 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
809 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
810 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
811 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
812 hint->relations = NIL;
813 hint->outer_inner = NULL;
815 return (Hint *) hint;
819 LeadingHintDelete(LeadingHint *hint)
824 list_free_deep(hint->relations);
825 if (hint->outer_inner)
826 pfree(hint->outer_inner);
831 SetHintCreate(const char *hint_str, const char *keyword,
832 HintKeyword hint_keyword)
836 hint = palloc(sizeof(SetHint));
837 hint->base.hint_str = hint_str;
838 hint->base.keyword = keyword;
839 hint->base.hint_keyword = hint_keyword;
840 hint->base.type = HINT_TYPE_SET;
841 hint->base.state = HINT_STATE_NOTUSED;
842 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
843 hint->base.desc_func = (HintDescFunction) SetHintDesc;
844 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
845 hint->base.parse_func = (HintParseFunction) SetHintParse;
850 return (Hint *) hint;
854 SetHintDelete(SetHint *hint)
864 list_free(hint->words);
869 RowsHintCreate(const char *hint_str, const char *keyword,
870 HintKeyword hint_keyword)
874 hint = palloc(sizeof(RowsHint));
875 hint->base.hint_str = hint_str;
876 hint->base.keyword = keyword;
877 hint->base.hint_keyword = hint_keyword;
878 hint->base.type = HINT_TYPE_ROWS;
879 hint->base.state = HINT_STATE_NOTUSED;
880 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
881 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
882 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
883 hint->base.parse_func = (HintParseFunction) RowsHintParse;
885 hint->inner_nrels = 0;
886 hint->relnames = NULL;
887 hint->joinrelids = NULL;
888 hint->inner_joinrelids = NULL;
889 hint->rows_str = NULL;
890 hint->value_type = RVT_ABSOLUTE;
893 return (Hint *) hint;
897 RowsHintDelete(RowsHint *hint)
906 for (i = 0; i < hint->nrels; i++)
907 pfree(hint->relnames[i]);
908 pfree(hint->relnames);
911 bms_free(hint->joinrelids);
912 bms_free(hint->inner_joinrelids);
917 ParallelHintCreate(const char *hint_str, const char *keyword,
918 HintKeyword hint_keyword)
922 hint = palloc(sizeof(ScanMethodHint));
923 hint->base.hint_str = hint_str;
924 hint->base.keyword = keyword;
925 hint->base.hint_keyword = hint_keyword;
926 hint->base.type = HINT_TYPE_PARALLEL;
927 hint->base.state = HINT_STATE_NOTUSED;
928 hint->base.delete_func = (HintDeleteFunction) ParallelHintDelete;
929 hint->base.desc_func = (HintDescFunction) ParallelHintDesc;
930 hint->base.cmp_func = (HintCmpFunction) ParallelHintCmp;
931 hint->base.parse_func = (HintParseFunction) ParallelHintParse;
932 hint->relname = NULL;
934 hint->nworkers_str = "0";
936 return (Hint *) hint;
940 ParallelHintDelete(ParallelHint *hint)
946 pfree(hint->relname);
952 HintStateCreate(void)
956 hstate = palloc(sizeof(HintState));
957 hstate->hint_str = NULL;
958 hstate->nall_hints = 0;
959 hstate->max_all_hints = 0;
960 hstate->all_hints = NULL;
961 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
962 hstate->scan_hints = NULL;
963 hstate->init_scan_mask = 0;
964 hstate->init_nworkers = 0;
965 hstate->init_min_para_size = 0;
966 hstate->init_paratup_cost = 0;
967 hstate->init_parasetup_cost = 0;
968 hstate->parent_relid = 0;
969 hstate->parent_scan_hint = NULL;
970 hstate->parent_parallel_hint = NULL;
971 hstate->parent_index_infos = NIL;
972 hstate->join_hints = NULL;
973 hstate->init_join_mask = 0;
974 hstate->join_hint_level = NULL;
975 hstate->leading_hint = NULL;
976 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
977 hstate->set_hints = NULL;
978 hstate->rows_hints = NULL;
979 hstate->parallel_hints = NULL;
985 HintStateDelete(HintState *hstate)
992 if (hstate->hint_str)
993 pfree(hstate->hint_str);
995 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
996 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
997 if (hstate->all_hints)
998 pfree(hstate->all_hints);
999 if (hstate->parent_index_infos)
1000 list_free(hstate->parent_index_infos);
1004 * Copy given value into buf, with quoting with '"' if necessary.
1007 quote_value(StringInfo buf, const char *value)
1009 bool need_quote = false;
1012 for (str = value; *str != '\0'; str++)
1014 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
1017 appendStringInfoCharMacro(buf, '"');
1022 for (str = value; *str != '\0'; str++)
1025 appendStringInfoCharMacro(buf, '"');
1027 appendStringInfoCharMacro(buf, *str);
1031 appendStringInfoCharMacro(buf, '"');
1035 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf)
1039 appendStringInfo(buf, "%s(", hint->base.keyword);
1040 if (hint->relname != NULL)
1042 quote_value(buf, hint->relname);
1043 foreach(l, hint->indexnames)
1045 appendStringInfoCharMacro(buf, ' ');
1046 quote_value(buf, (char *) lfirst(l));
1049 appendStringInfoString(buf, ")");
1051 appendStringInfoChar(buf, '\n');
1055 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf)
1059 appendStringInfo(buf, "%s(", hint->base.keyword);
1060 if (hint->relnames != NULL)
1062 quote_value(buf, hint->relnames[0]);
1063 for (i = 1; i < hint->nrels; i++)
1065 appendStringInfoCharMacro(buf, ' ');
1066 quote_value(buf, hint->relnames[i]);
1069 appendStringInfoString(buf, ")");
1071 appendStringInfoChar(buf, '\n');
1075 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
1077 if (outer_inner->relation == NULL)
1084 appendStringInfoCharMacro(buf, '(');
1085 foreach(l, outer_inner->outer_inner_pair)
1090 appendStringInfoCharMacro(buf, ' ');
1092 OuterInnerDesc(lfirst(l), buf);
1095 appendStringInfoCharMacro(buf, ')');
1098 quote_value(buf, outer_inner->relation);
1102 LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf)
1104 appendStringInfo(buf, "%s(", HINT_LEADING);
1105 if (hint->outer_inner == NULL)
1112 foreach(l, hint->relations)
1117 appendStringInfoCharMacro(buf, ' ');
1119 quote_value(buf, (char *) lfirst(l));
1123 OuterInnerDesc(hint->outer_inner, buf);
1125 appendStringInfoString(buf, ")");
1127 appendStringInfoChar(buf, '\n');
1131 SetHintDesc(SetHint *hint, StringInfo buf, bool nolf)
1133 bool is_first = true;
1136 appendStringInfo(buf, "%s(", HINT_SET);
1137 foreach(l, hint->words)
1142 appendStringInfoCharMacro(buf, ' ');
1144 quote_value(buf, (char *) lfirst(l));
1146 appendStringInfo(buf, ")");
1148 appendStringInfoChar(buf, '\n');
1152 RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf)
1156 appendStringInfo(buf, "%s(", hint->base.keyword);
1157 if (hint->relnames != NULL)
1159 quote_value(buf, hint->relnames[0]);
1160 for (i = 1; i < hint->nrels; i++)
1162 appendStringInfoCharMacro(buf, ' ');
1163 quote_value(buf, hint->relnames[i]);
1166 appendStringInfo(buf, " %s", hint->rows_str);
1167 appendStringInfoString(buf, ")");
1169 appendStringInfoChar(buf, '\n');
1173 ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf)
1175 appendStringInfo(buf, "%s(", hint->base.keyword);
1176 if (hint->relname != NULL)
1178 quote_value(buf, hint->relname);
1180 /* number of workers */
1181 appendStringInfoCharMacro(buf, ' ');
1182 quote_value(buf, hint->nworkers_str);
1183 /* application mode of num of workers */
1184 appendStringInfoCharMacro(buf, ' ');
1185 appendStringInfoString(buf,
1186 (hint->force_parallel ? "hard" : "soft"));
1188 appendStringInfoString(buf, ")");
1190 appendStringInfoChar(buf, '\n');
1194 * Append string which represents all hints in a given state to buf, with
1195 * preceding title with them.
1198 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1199 HintStatus state, bool nolf)
1203 appendStringInfo(buf, "%s:", title);
1205 appendStringInfoChar(buf, '\n');
1208 for (i = 0; i < hstate->nall_hints; i++)
1210 if (hstate->all_hints[i]->state != state)
1213 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf, nolf);
1217 if (nolf && nshown == 0)
1218 appendStringInfoString(buf, "(none)");
1222 * Dump contents of given hstate to server log with log level LOG.
1225 HintStateDump(HintState *hstate)
1231 elog(LOG, "pg_hint_plan:\nno hint");
1235 initStringInfo(&buf);
1237 appendStringInfoString(&buf, "pg_hint_plan:\n");
1238 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED, false);
1239 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED, false);
1240 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION, false);
1241 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR, false);
1243 elog(LOG, "%s", buf.data);
1249 HintStateDump2(HintState *hstate)
1255 elog(pg_hint_plan_message_level,
1256 "pg_hint_plan%s: HintStateDump: no hint", qnostr);
1260 initStringInfo(&buf);
1261 appendStringInfo(&buf, "pg_hint_plan%s: HintStateDump: ", qnostr);
1262 desc_hint_in_state(hstate, &buf, "{used hints", HINT_STATE_USED, true);
1263 desc_hint_in_state(hstate, &buf, "}, {not used hints", HINT_STATE_NOTUSED, true);
1264 desc_hint_in_state(hstate, &buf, "}, {duplicate hints", HINT_STATE_DUPLICATION, true);
1265 desc_hint_in_state(hstate, &buf, "}, {error hints", HINT_STATE_ERROR, true);
1266 appendStringInfoChar(&buf, '}');
1268 ereport(pg_hint_plan_message_level,
1270 errmsg("%s", buf.data)));
1280 RelnameCmp(const void *a, const void *b)
1282 const char *relnamea = *((const char **) a);
1283 const char *relnameb = *((const char **) b);
1285 return strcmp(relnamea, relnameb);
1289 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1291 return RelnameCmp(&a->relname, &b->relname);
1295 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1299 if (a->nrels != b->nrels)
1300 return a->nrels - b->nrels;
1302 for (i = 0; i < a->nrels; i++)
1305 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1313 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1319 SetHintCmp(const SetHint *a, const SetHint *b)
1321 return strcmp(a->name, b->name);
1325 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1329 if (a->nrels != b->nrels)
1330 return a->nrels - b->nrels;
1332 for (i = 0; i < a->nrels; i++)
1335 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1343 ParallelHintCmp(const ParallelHint *a, const ParallelHint *b)
1345 return RelnameCmp(&a->relname, &b->relname);
1349 HintCmp(const void *a, const void *b)
1351 const Hint *hinta = *((const Hint **) a);
1352 const Hint *hintb = *((const Hint **) b);
1354 if (hinta->type != hintb->type)
1355 return hinta->type - hintb->type;
1356 if (hinta->state == HINT_STATE_ERROR)
1358 if (hintb->state == HINT_STATE_ERROR)
1360 return hinta->cmp_func(hinta, hintb);
1364 * Returns byte offset of hint b from hint a. If hint a was specified before
1365 * b, positive value is returned.
1368 HintCmpWithPos(const void *a, const void *b)
1370 const Hint *hinta = *((const Hint **) a);
1371 const Hint *hintb = *((const Hint **) b);
1374 result = HintCmp(a, b);
1376 result = hinta->hint_str - hintb->hint_str;
1385 parse_keyword(const char *str, StringInfo buf)
1389 while (!isspace(*str) && *str != '(' && *str != '\0')
1390 appendStringInfoCharMacro(buf, *str++);
1396 skip_parenthesis(const char *str, char parenthesis)
1400 if (*str != parenthesis)
1402 if (parenthesis == '(')
1403 hint_ereport(str, ("Opening parenthesis is necessary."));
1404 else if (parenthesis == ')')
1405 hint_ereport(str, ("Closing parenthesis is necessary."));
1416 * Parse a token from str, and store malloc'd copy into word. A token can be
1417 * quoted with '"'. Return value is pointer to unparsed portion of original
1418 * string, or NULL if an error occurred.
1420 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1423 parse_quoted_value(const char *str, char **word, bool truncate)
1428 /* Skip leading spaces. */
1431 initStringInfo(&buf);
1444 /* Double quotation must be closed. */
1448 hint_ereport(str, ("Unterminated quoted string."));
1453 * Skip escaped double quotation.
1455 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1456 * block comments) to be an object name, so users must specify
1457 * alias for such object names.
1459 * Those special names can be allowed if we care escaped slashes
1460 * and asterisks, but we don't.
1469 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1473 appendStringInfoCharMacro(&buf, *str++);
1478 hint_ereport(str, ("Zero-length delimited string."));
1485 /* Truncate name if it's too long */
1487 truncate_identifier(buf.data, strlen(buf.data), true);
1494 static OuterInnerRels *
1495 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1497 OuterInnerRels *outer_inner;
1499 outer_inner = palloc(sizeof(OuterInnerRels));
1500 outer_inner->relation = name;
1501 outer_inner->outer_inner_pair = outer_inner_list;
1507 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1509 List *outer_inner_pair = NIL;
1511 if ((str = skip_parenthesis(str, '(')) == NULL)
1516 /* Store words in parentheses into outer_inner_list. */
1517 while(*str != ')' && *str != '\0')
1519 OuterInnerRels *outer_inner_rels;
1523 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1531 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1534 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1537 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1542 (str = skip_parenthesis(str, ')')) == NULL)
1544 list_free(outer_inner_pair);
1548 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1554 parse_parentheses_Leading(const char *str, List **name_list,
1555 OuterInnerRels **outer_inner)
1558 bool truncate = true;
1560 if ((str = skip_parenthesis(str, '(')) == NULL)
1566 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1571 /* Store words in parentheses into name_list. */
1572 while(*str != ')' && *str != '\0')
1574 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1576 list_free(*name_list);
1580 *name_list = lappend(*name_list, name);
1585 if ((str = skip_parenthesis(str, ')')) == NULL)
1591 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1594 bool truncate = true;
1596 if ((str = skip_parenthesis(str, '(')) == NULL)
1601 /* Store words in parentheses into name_list. */
1602 while(*str != ')' && *str != '\0')
1604 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1606 list_free(*name_list);
1610 *name_list = lappend(*name_list, name);
1613 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1614 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1615 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1616 keyword == HINT_KEYWORD_SET)
1622 if ((str = skip_parenthesis(str, ')')) == NULL)
1628 parse_hints(HintState *hstate, Query *parse, const char *str)
1633 initStringInfo(&buf);
1634 while (*str != '\0')
1636 const HintParser *parser;
1638 /* in error message, we output the comment including the keyword. */
1639 head = (char *) str;
1641 /* parse only the keyword of the hint. */
1642 resetStringInfo(&buf);
1643 str = parse_keyword(str, &buf);
1645 for (parser = parsers; parser->keyword != NULL; parser++)
1647 char *keyword = parser->keyword;
1650 if (strcasecmp(buf.data, keyword) != 0)
1653 hint = parser->create_func(head, keyword, parser->hint_keyword);
1655 /* parser of each hint does parse in a parenthesis. */
1656 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1658 hint->delete_func(hint);
1664 * Add hint information into all_hints array. If we don't have
1665 * enough space, double the array.
1667 if (hstate->nall_hints == 0)
1669 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1670 hstate->all_hints = (Hint **)
1671 palloc(sizeof(Hint *) * hstate->max_all_hints);
1673 else if (hstate->nall_hints == hstate->max_all_hints)
1675 hstate->max_all_hints *= 2;
1676 hstate->all_hints = (Hint **)
1677 repalloc(hstate->all_hints,
1678 sizeof(Hint *) * hstate->max_all_hints);
1681 hstate->all_hints[hstate->nall_hints] = hint;
1682 hstate->nall_hints++;
1689 if (parser->keyword == NULL)
1692 ("Unrecognized hint keyword \"%s\".", buf.data));
1703 * Get hints from table by client-supplied query string and application name.
1706 get_hints_from_table(const char *client_query, const char *client_application)
1708 const char *search_query =
1710 " FROM hint_plan.hints "
1711 " WHERE norm_query_string = $1 "
1712 " AND ( application_name = $2 "
1713 " OR application_name = '' ) "
1714 " ORDER BY application_name DESC";
1715 static SPIPlanPtr plan = NULL;
1717 Oid argtypes[2] = { TEXTOID, TEXTOID };
1719 bool nulls[2] = { false, false };
1725 hint_inhibit_level++;
1732 p = SPI_prepare(search_query, 2, argtypes);
1733 plan = SPI_saveplan(p);
1737 qry = cstring_to_text(client_query);
1738 app = cstring_to_text(client_application);
1739 values[0] = PointerGetDatum(qry);
1740 values[1] = PointerGetDatum(app);
1742 SPI_execute_plan(plan, values, nulls, true, 1);
1744 if (SPI_processed > 0)
1748 hints = SPI_getvalue(SPI_tuptable->vals[0],
1749 SPI_tuptable->tupdesc, 1);
1751 * Here we use SPI_palloc to ensure that hints string is valid even
1752 * after SPI_finish call. We can't use simple palloc because it
1753 * allocates memory in SPI's context and that context is deleted in
1756 buf = SPI_palloc(strlen(hints) + 1);
1763 hint_inhibit_level--;
1767 hint_inhibit_level--;
1776 * Get client-supplied query string.
1779 get_query_string(void)
1783 if (plpgsql_recurse_level > 0)
1786 * This is quite ugly but this is the only point I could find where
1787 * we can get the query string.
1789 p = (char*)error_context_stack->arg;
1793 PreparedStatement *entry;
1795 entry = FetchPreparedStatement(stmt_name, true);
1796 p = entry->plansource->query_string;
1799 p = debug_query_string;
1805 * Get hints from the head block comment in client-supplied query string.
1808 get_hints_from_comment(const char *p)
1810 const char *hint_head;
1818 /* extract query head comment. */
1819 hint_head = strstr(p, HINT_START);
1820 if (hint_head == NULL)
1822 for (;p < hint_head; p++)
1825 * Allow these characters precedes hint comment:
1827 * - alphabets which are in ASCII range
1828 * - space, tabs and new-lines
1829 * - underscores, for identifier
1830 * - commas, for SELECT clause, EXPLAIN and PREPARE
1831 * - parentheses, for EXPLAIN and PREPARE
1833 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1834 * avoid behavior which depends on locale setting.
1836 if (!(*p >= '0' && *p <= '9') &&
1837 !(*p >= 'A' && *p <= 'Z') &&
1838 !(*p >= 'a' && *p <= 'z') &&
1842 *p != '(' && *p != ')')
1846 len = strlen(HINT_START);
1851 /* find hint end keyword. */
1852 if ((tail = strstr(p, HINT_END)) == NULL)
1854 hint_ereport(head, ("Unterminated block comment."));
1858 /* We don't support nested block comments. */
1859 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1861 hint_ereport(head, ("Nested block comments are not supported."));
1865 /* Make a copy of hint. */
1867 head = palloc(len + 1);
1868 memcpy(head, p, len);
1876 * Parse hints that got, create hint struct from parse tree and parse hints.
1879 create_hintstate(Query *parse, const char *hints)
1888 /* -1 means that no Parallel hint is specified. */
1889 max_hint_nworkers = -1;
1892 hstate = HintStateCreate();
1893 hstate->hint_str = (char *) hints;
1895 /* parse each hint. */
1896 parse_hints(hstate, parse, p);
1898 /* When nothing specified a hint, we free HintState and returns NULL. */
1899 if (hstate->nall_hints == 0)
1901 HintStateDelete(hstate);
1905 /* Sort hints in order of original position. */
1906 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1909 /* Count number of hints per hint-type. */
1910 for (i = 0; i < hstate->nall_hints; i++)
1912 Hint *cur_hint = hstate->all_hints[i];
1913 hstate->num_hints[cur_hint->type]++;
1917 * If an object (or a set of objects) has multiple hints of same hint-type,
1918 * only the last hint is valid and others are ignored in planning.
1919 * Hints except the last are marked as 'duplicated' to remember the order.
1921 for (i = 0; i < hstate->nall_hints - 1; i++)
1923 Hint *cur_hint = hstate->all_hints[i];
1924 Hint *next_hint = hstate->all_hints[i + 1];
1927 * Leading hint is marked as 'duplicated' in transform_join_hints.
1929 if (cur_hint->type == HINT_TYPE_LEADING &&
1930 next_hint->type == HINT_TYPE_LEADING)
1934 * Note that we need to pass addresses of hint pointers, because
1935 * HintCmp is designed to sort array of Hint* by qsort.
1937 if (HintCmp(&cur_hint, &next_hint) == 0)
1939 hint_ereport(cur_hint->hint_str,
1940 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1941 cur_hint->state = HINT_STATE_DUPLICATION;
1946 * Make sure that per-type array pointers point proper position in the
1947 * array which consists of all hints.
1949 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1950 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1951 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1952 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1953 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1954 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1955 hstate->num_hints[HINT_TYPE_LEADING]);
1956 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1957 hstate->num_hints[HINT_TYPE_SET]);
1958 hstate->parallel_hints = (ParallelHint **) (hstate->set_hints +
1959 hstate->num_hints[HINT_TYPE_ROWS]);
1965 * Parse inside of parentheses of scan-method hints.
1968 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1971 const char *keyword = hint->base.keyword;
1972 HintKeyword hint_keyword = hint->base.hint_keyword;
1973 List *name_list = NIL;
1976 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1979 /* Parse relation name and index name(s) if given hint accepts. */
1980 length = list_length(name_list);
1982 /* at least twp parameters required */
1986 ("%s hint requires a relation.", hint->base.keyword));
1987 hint->base.state = HINT_STATE_ERROR;
1991 hint->relname = linitial(name_list);
1992 hint->indexnames = list_delete_first(name_list);
1994 /* check whether the hint accepts index name(s) */
1995 if (length > 1 && !SCAN_HINT_ACCEPTS_INDEX_NAMES(hint_keyword))
1998 ("%s hint accepts only one relation.",
1999 hint->base.keyword));
2000 hint->base.state = HINT_STATE_ERROR;
2004 /* Set a bit for specified hint. */
2005 switch (hint_keyword)
2007 case HINT_KEYWORD_SEQSCAN:
2008 hint->enforce_mask = ENABLE_SEQSCAN;
2010 case HINT_KEYWORD_INDEXSCAN:
2011 hint->enforce_mask = ENABLE_INDEXSCAN;
2013 case HINT_KEYWORD_INDEXSCANREGEXP:
2014 hint->enforce_mask = ENABLE_INDEXSCAN;
2015 hint->regexp = true;
2017 case HINT_KEYWORD_BITMAPSCAN:
2018 hint->enforce_mask = ENABLE_BITMAPSCAN;
2020 case HINT_KEYWORD_BITMAPSCANREGEXP:
2021 hint->enforce_mask = ENABLE_BITMAPSCAN;
2022 hint->regexp = true;
2024 case HINT_KEYWORD_TIDSCAN:
2025 hint->enforce_mask = ENABLE_TIDSCAN;
2027 case HINT_KEYWORD_NOSEQSCAN:
2028 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
2030 case HINT_KEYWORD_NOINDEXSCAN:
2031 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
2033 case HINT_KEYWORD_NOBITMAPSCAN:
2034 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
2036 case HINT_KEYWORD_NOTIDSCAN:
2037 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
2039 case HINT_KEYWORD_INDEXONLYSCAN:
2040 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2042 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
2043 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
2044 hint->regexp = true;
2046 case HINT_KEYWORD_NOINDEXONLYSCAN:
2047 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
2050 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2059 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
2062 const char *keyword = hint->base.keyword;
2063 HintKeyword hint_keyword = hint->base.hint_keyword;
2064 List *name_list = NIL;
2066 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2069 hint->nrels = list_length(name_list);
2071 if (hint->nrels > 0)
2077 * Transform relation names from list to array to sort them with qsort
2080 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2081 foreach (l, name_list)
2083 hint->relnames[i] = lfirst(l);
2088 list_free(name_list);
2090 /* A join hint requires at least two relations */
2091 if (hint->nrels < 2)
2094 ("%s hint requires at least two relations.",
2095 hint->base.keyword));
2096 hint->base.state = HINT_STATE_ERROR;
2100 /* Sort hints in alphabetical order of relation names. */
2101 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2103 switch (hint_keyword)
2105 case HINT_KEYWORD_NESTLOOP:
2106 hint->enforce_mask = ENABLE_NESTLOOP;
2108 case HINT_KEYWORD_MERGEJOIN:
2109 hint->enforce_mask = ENABLE_MERGEJOIN;
2111 case HINT_KEYWORD_HASHJOIN:
2112 hint->enforce_mask = ENABLE_HASHJOIN;
2114 case HINT_KEYWORD_NONESTLOOP:
2115 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
2117 case HINT_KEYWORD_NOMERGEJOIN:
2118 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
2120 case HINT_KEYWORD_NOHASHJOIN:
2121 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
2124 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
2133 OuterInnerPairCheck(OuterInnerRels *outer_inner)
2136 if (outer_inner->outer_inner_pair == NIL)
2138 if (outer_inner->relation)
2144 if (list_length(outer_inner->outer_inner_pair) == 2)
2146 foreach(l, outer_inner->outer_inner_pair)
2148 if (!OuterInnerPairCheck(lfirst(l)))
2159 OuterInnerList(OuterInnerRels *outer_inner)
2161 List *outer_inner_list = NIL;
2163 OuterInnerRels *outer_inner_rels;
2165 foreach(l, outer_inner->outer_inner_pair)
2167 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2169 if (outer_inner_rels->relation != NULL)
2170 outer_inner_list = lappend(outer_inner_list,
2171 outer_inner_rels->relation);
2173 outer_inner_list = list_concat(outer_inner_list,
2174 OuterInnerList(outer_inner_rels));
2176 return outer_inner_list;
2180 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
2183 List *name_list = NIL;
2184 OuterInnerRels *outer_inner = NULL;
2186 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
2190 if (outer_inner != NULL)
2191 name_list = OuterInnerList(outer_inner);
2193 hint->relations = name_list;
2194 hint->outer_inner = outer_inner;
2196 /* A Leading hint requires at least two relations */
2197 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
2199 hint_ereport(hint->base.hint_str,
2200 ("%s hint requires at least two relations.",
2202 hint->base.state = HINT_STATE_ERROR;
2204 else if (hint->outer_inner != NULL &&
2205 !OuterInnerPairCheck(hint->outer_inner))
2207 hint_ereport(hint->base.hint_str,
2208 ("%s hint requires two sets of relations when parentheses nests.",
2210 hint->base.state = HINT_STATE_ERROR;
2217 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2219 List *name_list = NIL;
2221 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2225 hint->words = name_list;
2227 /* We need both name and value to set GUC parameter. */
2228 if (list_length(name_list) == 2)
2230 hint->name = linitial(name_list);
2231 hint->value = lsecond(name_list);
2235 hint_ereport(hint->base.hint_str,
2236 ("%s hint requires name and value of GUC parameter.",
2238 hint->base.state = HINT_STATE_ERROR;
2245 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2248 HintKeyword hint_keyword = hint->base.hint_keyword;
2249 List *name_list = NIL;
2253 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2256 /* Last element must be rows specification */
2257 hint->nrels = list_length(name_list) - 1;
2259 if (hint->nrels > 0)
2265 * Transform relation names from list to array to sort them with qsort
2268 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2269 foreach (l, name_list)
2271 if (hint->nrels <= i)
2273 hint->relnames[i] = lfirst(l);
2278 /* Retieve rows estimation */
2279 rows_str = list_nth(name_list, hint->nrels);
2280 hint->rows_str = rows_str; /* store as-is for error logging */
2281 if (rows_str[0] == '#')
2283 hint->value_type = RVT_ABSOLUTE;
2286 else if (rows_str[0] == '+')
2288 hint->value_type = RVT_ADD;
2291 else if (rows_str[0] == '-')
2293 hint->value_type = RVT_SUB;
2296 else if (rows_str[0] == '*')
2298 hint->value_type = RVT_MULTI;
2303 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2304 hint->base.state = HINT_STATE_ERROR;
2307 hint->rows = strtod(rows_str, &end_ptr);
2310 hint_ereport(rows_str,
2311 ("%s hint requires valid number as rows estimation.",
2312 hint->base.keyword));
2313 hint->base.state = HINT_STATE_ERROR;
2317 /* A join hint requires at least two relations */
2318 if (hint->nrels < 2)
2321 ("%s hint requires at least two relations.",
2322 hint->base.keyword));
2323 hint->base.state = HINT_STATE_ERROR;
2327 list_free(name_list);
2329 /* Sort relnames in alphabetical order. */
2330 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2336 ParallelHintParse(ParallelHint *hint, HintState *hstate, Query *parse,
2339 HintKeyword hint_keyword = hint->base.hint_keyword;
2340 List *name_list = NIL;
2344 bool force_parallel = false;
2346 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2349 /* Parse relation name and index name(s) if given hint accepts. */
2350 length = list_length(name_list);
2352 if (length < 2 || length > 3)
2355 ("wrong number of arguments (%d): %s",
2356 length, hint->base.keyword));
2357 hint->base.state = HINT_STATE_ERROR;
2361 hint->relname = linitial(name_list);
2363 /* The second parameter is number of workers */
2364 hint->nworkers_str = list_nth(name_list, 1);
2365 nworkers = strtod(hint->nworkers_str, &end_ptr);
2366 if (*end_ptr || nworkers < 0 || nworkers > max_worker_processes)
2369 hint_ereport(hint->nworkers_str,
2370 ("number of workers must be a number: %s",
2371 hint->base.keyword));
2372 else if (nworkers < 0)
2373 hint_ereport(hint->nworkers_str,
2374 ("number of workers must be positive: %s",
2375 hint->base.keyword));
2376 else if (nworkers > max_worker_processes)
2377 hint_ereport(hint->nworkers_str,
2378 ("number of workers = %d is larger than max_worker_processes(%d): %s",
2379 nworkers, max_worker_processes, hint->base.keyword));
2381 hint->base.state = HINT_STATE_ERROR;
2384 hint->nworkers = nworkers;
2386 /* optional third parameter is specified */
2389 const char *modeparam = (const char *)list_nth(name_list, 2);
2390 if (strcasecmp(modeparam, "hard") == 0)
2391 force_parallel = true;
2392 else if (strcasecmp(modeparam, "soft") != 0)
2394 hint_ereport(modeparam,
2395 ("enforcement must be soft or hard: %s",
2396 hint->base.keyword));
2397 hint->base.state = HINT_STATE_ERROR;
2401 hint->force_parallel = force_parallel;
2403 if (hint->base.state != HINT_STATE_ERROR &&
2404 nworkers > max_hint_nworkers)
2405 max_hint_nworkers = nworkers;
2411 * set GUC parameter functions
2415 get_current_scan_mask()
2420 mask |= ENABLE_SEQSCAN;
2421 if (enable_indexscan)
2422 mask |= ENABLE_INDEXSCAN;
2423 if (enable_bitmapscan)
2424 mask |= ENABLE_BITMAPSCAN;
2426 mask |= ENABLE_TIDSCAN;
2427 if (enable_indexonlyscan)
2428 mask |= ENABLE_INDEXONLYSCAN;
2434 get_current_join_mask()
2438 if (enable_nestloop)
2439 mask |= ENABLE_NESTLOOP;
2440 if (enable_mergejoin)
2441 mask |= ENABLE_MERGEJOIN;
2442 if (enable_hashjoin)
2443 mask |= ENABLE_HASHJOIN;
2449 * Sets GUC prameters without throwing exception. Reutrns false if something
2453 set_config_option_noerror(const char *name, const char *value,
2454 GucContext context, GucSource source,
2455 GucAction action, bool changeVal, int elevel)
2458 MemoryContext ccxt = CurrentMemoryContext;
2462 result = set_config_option(name, value, context, source,
2463 action, changeVal, 0, false);
2469 /* Save error info */
2470 MemoryContextSwitchTo(ccxt);
2471 errdata = CopyErrorData();
2475 (errcode(errdata->sqlerrcode),
2476 errhidestmt(hidestmt),
2477 errmsg("%s", errdata->message),
2478 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2479 errdata->hint ? errhint("%s", errdata->hint) : 0));
2480 FreeErrorData(errdata);
2488 * Sets GUC parameter of int32 type without throwing exceptions. Returns false
2489 * if something wrong.
2492 set_config_int32_option(const char *name, int32 value, GucContext context)
2494 char buf[16]; /* enough for int32 */
2496 if (snprintf(buf, 16, "%d", value) < 0)
2498 ereport(pg_hint_plan_message_level,
2499 (errmsg ("Cannot set integer value: %d: %s",
2500 max_hint_nworkers, strerror(errno))));
2505 set_config_option_noerror(name, buf, context,
2506 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2507 pg_hint_plan_message_level);
2510 /* setup scan method enforcement according to given options */
2512 setup_guc_enforcement(SetHint **options, int noptions, GucContext context)
2516 for (i = 0; i < noptions; i++)
2518 SetHint *hint = options[i];
2521 if (!hint_state_enabled(hint))
2524 result = set_config_option_noerror(hint->name, hint->value, context,
2525 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2526 pg_hint_plan_message_level);
2528 hint->base.state = HINT_STATE_USED;
2530 hint->base.state = HINT_STATE_ERROR;
2537 * Setup parallel execution environment.
2539 * If hint is not NULL, set up using it, elsewise reset to initial environment.
2542 setup_parallel_plan_enforcement(ParallelHint *hint, HintState *state)
2546 hint->base.state = HINT_STATE_USED;
2547 set_config_int32_option("max_parallel_workers_per_gather",
2548 hint->nworkers, state->context);
2551 set_config_int32_option("max_parallel_workers_per_gather",
2552 state->init_nworkers, state->context);
2554 /* force means that enforce parallel as far as possible */
2555 if (hint && hint->force_parallel)
2557 set_config_int32_option("parallel_tuple_cost", 0, state->context);
2558 set_config_int32_option("parallel_setup_cost", 0, state->context);
2559 set_config_int32_option("min_parallel_relation_size", 0,
2564 set_config_int32_option("parallel_tuple_cost",
2565 state->init_paratup_cost, state->context);
2566 set_config_int32_option("parallel_setup_cost",
2567 state->init_parasetup_cost, state->context);
2568 set_config_int32_option("min_parallel_relation_size",
2569 state->init_min_para_size, state->context);
2573 #define SET_CONFIG_OPTION(name, type_bits) \
2574 set_config_option_noerror((name), \
2575 (mask & (type_bits)) ? "true" : "false", \
2576 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2580 * Setup GUC environment to enforce scan methods. If scanhint is NULL, reset
2581 * GUCs to the saved state in state.
2584 setup_scan_method_enforcement(ScanMethodHint *scanhint, HintState *state)
2586 unsigned char enforce_mask = state->init_scan_mask;
2587 GucContext context = state->context;
2592 enforce_mask = scanhint->enforce_mask;
2593 scanhint->base.state = HINT_STATE_USED;
2596 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2597 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2598 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2600 mask = enforce_mask;
2602 mask = enforce_mask & current_hint_state->init_scan_mask;
2604 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2605 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2606 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2607 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2608 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2612 set_join_config_options(unsigned char enforce_mask, GucContext context)
2616 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2617 enforce_mask == ENABLE_HASHJOIN)
2618 mask = enforce_mask;
2620 mask = enforce_mask & current_hint_state->init_join_mask;
2622 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2623 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2624 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2628 * pg_hint_plan hook functions
2632 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2633 ProcessUtilityContext context,
2634 ParamListInfo params,
2635 DestReceiver *dest, char *completionTag)
2640 * Use standard planner if pg_hint_plan is disabled or current nesting
2641 * depth is nesting depth of SPI calls.
2643 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2645 if (debug_level > 1)
2646 ereport(pg_hint_plan_message_level,
2647 (errmsg ("pg_hint_plan: ProcessUtility:"
2648 " pg_hint_plan.enable_hint = off")));
2649 if (prev_ProcessUtility)
2650 (*prev_ProcessUtility) (parsetree, queryString,
2652 dest, completionTag);
2654 standard_ProcessUtility(parsetree, queryString,
2656 dest, completionTag);
2661 if (IsA(node, ExplainStmt))
2664 * Draw out parse tree of actual query from Query struct of EXPLAIN
2670 stmt = (ExplainStmt *) node;
2672 Assert(IsA(stmt->query, Query));
2673 query = (Query *) stmt->query;
2675 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2676 node = query->utilityStmt;
2680 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2681 * specified to preceding PREPARE command to use it as source of hints.
2683 if (IsA(node, ExecuteStmt))
2687 stmt = (ExecuteStmt *) node;
2688 stmt_name = stmt->name;
2692 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2695 if (IsA(node, CreateTableAsStmt))
2697 CreateTableAsStmt *stmt;
2700 stmt = (CreateTableAsStmt *) node;
2701 Assert(IsA(stmt->query, Query));
2702 query = (Query *) stmt->query;
2704 if (query->commandType == CMD_UTILITY &&
2705 IsA(query->utilityStmt, ExecuteStmt))
2707 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2708 stmt_name = estmt->name;
2714 if (debug_level > 1)
2715 ereport(pg_hint_plan_message_level,
2716 (errmsg ("pg_hint_plan: ProcessUtility:"
2717 " stmt_name = \"%s\", statement=\"%s\"",
2718 stmt_name, queryString)));
2722 if (prev_ProcessUtility)
2723 (*prev_ProcessUtility) (parsetree, queryString,
2725 dest, completionTag);
2727 standard_ProcessUtility(parsetree, queryString,
2729 dest, completionTag);
2743 if (prev_ProcessUtility)
2744 (*prev_ProcessUtility) (parsetree, queryString,
2746 dest, completionTag);
2748 standard_ProcessUtility(parsetree, queryString,
2750 dest, completionTag);
2754 * Push a hint into hint stack which is implemented with List struct. Head of
2755 * list is top of stack.
2758 push_hint(HintState *hstate)
2760 /* Prepend new hint to the list means pushing to stack. */
2761 HintStateStack = lcons(hstate, HintStateStack);
2763 /* Pushed hint is the one which should be used hereafter. */
2764 current_hint_state = hstate;
2767 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2771 /* Hint stack must not be empty. */
2772 if(HintStateStack == NIL)
2773 elog(ERROR, "hint stack is empty");
2776 * Take a hint at the head from the list, and free it. Switch
2777 * current_hint_state to point new head (NULL if the list is empty).
2779 HintStateStack = list_delete_first(HintStateStack);
2780 HintStateDelete(current_hint_state);
2781 if(HintStateStack == NIL)
2782 current_hint_state = NULL;
2784 current_hint_state = (HintState *) lfirst(list_head(HintStateStack));
2787 static PlannedStmt *
2788 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2790 const char *hints = NULL;
2793 pgssJumbleState jstate;
2796 PlannedStmt *result;
2802 if (debug_level > 1)
2803 snprintf(qnostr, sizeof(qnostr), "[qno=0x%x]", qno++);
2807 * Use standard planner if pg_hint_plan is disabled or current nesting
2808 * depth is nesting depth of SPI calls. Other hook functions try to change
2809 * plan with current_hint_state if any, so set it to NULL.
2811 if (!pg_hint_plan_enable_hint || hint_inhibit_level > 0)
2813 if (debug_level > 1)
2814 elog(pg_hint_plan_message_level,
2815 "pg_hint_plan%s: planner: enable_hint=%d,"
2816 " hint_inhibit_level=%d",
2817 qnostr, pg_hint_plan_enable_hint, hint_inhibit_level);
2820 goto standard_planner_proc;
2823 /* Create hint struct from client-supplied query string. */
2824 query = get_query_string();
2827 * Create hintstate from hint specified for the query, if any.
2829 * First we lookup hint in pg_hint.hints table by normalized query string,
2830 * unless pg_hint_plan.enable_hint_table is OFF.
2831 * This parameter provides option to avoid overhead of table lookup during
2834 * If no hint was found, then we try to get hint from special query comment.
2836 if (pg_hint_plan_enable_hint_table)
2839 * Search hint information which is stored for the query and the
2840 * application. Query string is normalized before using in condition
2841 * in order to allow fuzzy matching.
2843 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2844 * careful when supporting PostgreSQL's version up.
2846 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2847 jstate.jumble_len = 0;
2848 jstate.clocations_buf_size = 32;
2849 jstate.clocations = (pgssLocationLen *)
2850 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2851 jstate.clocations_count = 0;
2852 JumbleQuery(&jstate, parse);
2854 * generate_normalized_query() copies exact given query_len bytes, so we
2855 * add 1 byte for null-termination here. As comments on
2856 * generate_normalized_query says, generate_normalized_query doesn't
2857 * take care of null-terminate, but additional 1 byte ensures that '\0'
2858 * byte in the source buffer to be copied into norm_query.
2860 query_len = strlen(query) + 1;
2861 norm_query = generate_normalized_query(&jstate,
2864 GetDatabaseEncoding());
2865 hints = get_hints_from_table(norm_query, application_name);
2866 if (debug_level > 1)
2869 snprintf(msgstr, 1024, "hints from table: \"%s\":"
2870 " normalzed_query=\"%s\", application name =\"%s\"",
2871 hints, norm_query, application_name);
2874 ereport(pg_hint_plan_message_level,
2875 (errhidestmt(hidestmt),
2876 errmsg("pg_hint_plan%s:"
2877 " no match found in table:"
2878 " application name = \"%s\","
2879 " normalzed_query=\"%s\"",
2880 qnostr, application_name, norm_query)));
2887 hints = get_hints_from_comment(query);
2889 if (debug_level > 1)
2891 snprintf(msgstr, 1024, "hints in comment=\"%s\"",
2892 hints ? hints : "(none)");
2893 if (debug_level > 2 ||
2894 stmt_name || strcmp(query, debug_query_string))
2895 snprintf(msgstr + strlen(msgstr), 1024- strlen(msgstr),
2896 ", stmt=\"%s\", query=\"%s\", debug_query_string=\"%s\"",
2897 stmt_name, query, debug_query_string);
2901 hstate = create_hintstate(parse, hints);
2904 * Use standard planner if the statement has not valid hint. Other hook
2905 * functions try to change plan with current_hint_state if any, so set it
2909 goto standard_planner_proc;
2912 * Push new hint struct to the hint stack to disable previous hint context.
2916 /* Set scan enforcement here. */
2917 save_nestlevel = NewGUCNestLevel();
2919 /* Apply Set hints, then save it as the initial state */
2920 setup_guc_enforcement(current_hint_state->set_hints,
2921 current_hint_state->num_hints[HINT_TYPE_SET],
2922 current_hint_state->context);
2924 current_hint_state->init_scan_mask = get_current_scan_mask();
2925 current_hint_state->init_join_mask = get_current_join_mask();
2926 current_hint_state->init_min_para_size = min_parallel_relation_size;
2927 current_hint_state->init_paratup_cost = parallel_tuple_cost;
2928 current_hint_state->init_parasetup_cost = parallel_setup_cost;
2931 * max_parallel_workers_per_gather should be non-zero here if Workers hint
2934 if (max_hint_nworkers > 0 && max_parallel_workers_per_gather < 1)
2935 set_config_int32_option("max_parallel_workers_per_gather",
2936 1, current_hint_state->context);
2937 current_hint_state->init_nworkers = max_parallel_workers_per_gather;
2939 if (debug_level > 1)
2941 ereport(pg_hint_plan_message_level,
2942 (errhidestmt(hidestmt),
2943 errmsg("pg_hint_plan%s: planner: %s",
2949 * Use PG_TRY mechanism to recover GUC parameters and current_hint_state to
2950 * the state when this planner started when error occurred in planner.
2955 result = (*prev_planner) (parse, cursorOptions, boundParams);
2957 result = standard_planner(parse, cursorOptions, boundParams);
2962 * Rollback changes of GUC parameters, and pop current hint context
2963 * from hint stack to rewind the state.
2965 AtEOXact_GUC(true, save_nestlevel);
2971 /* Print hint in debug mode. */
2972 if (debug_level == 1)
2973 HintStateDump(current_hint_state);
2974 else if (debug_level > 1)
2975 HintStateDump2(current_hint_state);
2978 * Rollback changes of GUC parameters, and pop current hint context from
2979 * hint stack to rewind the state.
2981 AtEOXact_GUC(true, save_nestlevel);
2986 standard_planner_proc:
2987 if (debug_level > 1)
2989 ereport(pg_hint_plan_message_level,
2990 (errhidestmt(hidestmt),
2991 errmsg("pg_hint_plan%s: planner: no valid hint (%s)",
2995 current_hint_state = NULL;
2997 return (*prev_planner) (parse, cursorOptions, boundParams);
2999 return standard_planner(parse, cursorOptions, boundParams);
3003 * Find scan method hint to be applied to the given relation
3006 static ScanMethodHint *
3007 find_scan_hint(PlannerInfo *root, Index relid)
3011 ScanMethodHint *real_name_hint = NULL;
3012 ScanMethodHint *alias_hint = NULL;
3015 /* This should not be a join rel */
3017 rel = root->simple_rel_array[relid];
3020 * This function is called for any RelOptInfo or its inheritance parent if
3021 * any. If we are called from inheritance planner, the RelOptInfo for the
3022 * parent of target child relation is not set in the planner info.
3024 * Otherwise we should check that the reloptinfo is base relation or
3025 * inheritance children.
3028 rel->reloptkind != RELOPT_BASEREL &&
3029 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3033 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3035 rte = root->simple_rte_array[relid];
3038 /* We don't hint on other than relation and foreign tables */
3039 if (rte->rtekind != RTE_RELATION ||
3040 rte->relkind == RELKIND_FOREIGN_TABLE)
3043 /* Find scan method hint, which matches given names, from the list. */
3044 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
3046 ScanMethodHint *hint = current_hint_state->scan_hints[i];
3048 /* We ignore disabled hints. */
3049 if (!hint_state_enabled(hint))
3053 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3056 /* check the real name for appendrel children */
3057 if (!real_name_hint &&
3058 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3060 char *realname = get_rel_name(rte->relid);
3062 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3063 real_name_hint = hint;
3066 /* No more match expected, break */
3067 if(alias_hint && real_name_hint)
3071 /* real name match precedes alias match */
3073 return real_name_hint;
3078 static ParallelHint *
3079 find_parallel_hint(PlannerInfo *root, Index relid)
3083 ParallelHint *real_name_hint = NULL;
3084 ParallelHint *alias_hint = NULL;
3087 /* This should not be a join rel */
3089 rel = root->simple_rel_array[relid];
3092 * This function is called for any RelOptInfo or its inheritance parent if
3093 * any. If we are called from inheritance planner, the RelOptInfo for the
3094 * parent of target child relation is not set in the planner info.
3096 * Otherwise we should check that the reloptinfo is base relation or
3097 * inheritance children.
3100 rel->reloptkind != RELOPT_BASEREL &&
3101 rel->reloptkind != RELOPT_OTHER_MEMBER_REL)
3105 * This is baserel or appendrel children. We can refer to RangeTblEntry.
3107 rte = root->simple_rte_array[relid];
3110 /* We don't hint on other than relation and foreign tables */
3111 if (rte->rtekind != RTE_RELATION ||
3112 rte->relkind == RELKIND_FOREIGN_TABLE)
3115 /* Find parallel method hint, which matches given names, from the list. */
3116 for (i = 0; i < current_hint_state->num_hints[HINT_TYPE_PARALLEL]; i++)
3118 ParallelHint *hint = current_hint_state->parallel_hints[i];
3120 /* We ignore disabled hints. */
3121 if (!hint_state_enabled(hint))
3125 RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
3128 /* check the real name for appendrel children */
3129 if (!real_name_hint &&
3130 rel && rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3132 char *realname = get_rel_name(rte->relid);
3134 if (realname && RelnameCmp(&realname, &hint->relname) == 0)
3135 real_name_hint = hint;
3138 /* No more match expected, break */
3139 if(alias_hint && real_name_hint)
3143 /* real name match precedes alias match */
3145 return real_name_hint;
3153 * Returns TRUE on match, FALSE on no match.
3155 * s1 --- the data to match against
3156 * s2 --- the pattern
3158 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
3161 regexpeq(const char *s1, const char *s2)
3167 strcpy(name.data, s1);
3168 regexp = cstring_to_text(s2);
3170 result = DirectFunctionCall2Coll(nameregexeq,
3171 DEFAULT_COLLATION_OID,
3172 NameGetDatum(&name),
3173 PointerGetDatum(regexp));
3174 return DatumGetBool(result);
3178 /* Remove indexes instructed not to use by hint. */
3180 restrict_indexes(PlannerInfo *root, ScanMethodHint *hint, RelOptInfo *rel,
3181 bool using_parent_hint)
3187 RangeTblEntry *rte = root->simple_rte_array[rel->relid];
3188 Oid relationObjectId = rte->relid;
3191 * We delete all the IndexOptInfo list and prevent you from being usable by
3194 if (hint->enforce_mask == ENABLE_SEQSCAN ||
3195 hint->enforce_mask == ENABLE_TIDSCAN)
3197 list_free_deep(rel->indexlist);
3198 rel->indexlist = NIL;
3199 hint->base.state = HINT_STATE_USED;
3205 * When a list of indexes is not specified, we just use all indexes.
3207 if (hint->indexnames == NIL)
3211 * Leaving only an specified index, we delete it from a IndexOptInfo list
3215 if (debug_level > 0)
3216 initStringInfo(&buf);
3218 for (cell = list_head(rel->indexlist); cell; cell = next)
3220 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
3221 char *indexname = get_rel_name(info->indexoid);
3223 bool use_index = false;
3227 foreach(l, hint->indexnames)
3229 char *hintname = (char *) lfirst(l);
3233 result = regexpeq(indexname, hintname);
3235 result = RelnameCmp(&indexname, &hintname) == 0;
3240 if (debug_level > 0)
3242 appendStringInfoCharMacro(&buf, ' ');
3243 quote_value(&buf, indexname);
3251 * Apply index restriction of parent hint to children. Since index
3252 * inheritance is not explicitly described we should search for an
3253 * children's index with the same definition to that of the parent.
3255 if (using_parent_hint && !use_index)
3257 foreach(l, current_hint_state->parent_index_infos)
3261 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
3264 * we check the 'same' index by comparing uniqueness, access
3265 * method and index key columns.
3267 if (p_info->indisunique != info->unique ||
3268 p_info->method != info->relam ||
3269 list_length(p_info->column_names) != info->ncolumns)
3272 /* Check if index key columns match */
3273 for (i = 0; i < info->ncolumns; i++)
3275 char *c_attname = NULL;
3276 char *p_attname = NULL;
3278 p_attname = list_nth(p_info->column_names, i);
3281 * if both of the key of the same position are expressions,
3282 * ignore them for now and check later.
3284 if (info->indexkeys[i] == 0 && !p_attname)
3287 /* deny if one is expression while another is not */
3288 if (info->indexkeys[i] == 0 || !p_attname)
3291 c_attname = get_attname(relationObjectId,
3292 info->indexkeys[i]);
3294 /* deny if any of column attributes don't match */
3295 if (strcmp(p_attname, c_attname) != 0 ||
3296 p_info->indcollation[i] != info->indexcollations[i] ||
3297 p_info->opclass[i] != info->opcintype[i]||
3298 ((p_info->indoption[i] & INDOPTION_DESC) != 0)
3299 != info->reverse_sort[i] ||
3300 ((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0)
3301 != info->nulls_first[i])
3305 /* deny this if any difference found */
3306 if (i != info->ncolumns)
3309 /* check on key expressions */
3310 if ((p_info->expression_str && (info->indexprs != NIL)) ||
3311 (p_info->indpred_str && (info->indpred != NIL)))
3313 /* fetch the index of this child */
3314 ht_idx = SearchSysCache1(INDEXRELID,
3315 ObjectIdGetDatum(info->indexoid));
3317 /* check expressions if both expressions are available */
3318 if (p_info->expression_str &&
3319 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
3326 * to change the expression's parameter of child's
3329 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3330 Anum_pg_index_indexprs,
3333 result = DirectFunctionCall2(pg_get_expr,
3338 /* deny if expressions don't match */
3339 if (strcmp(p_info->expression_str,
3340 text_to_cstring(DatumGetTextP(result))) != 0)
3343 ReleaseSysCache(ht_idx);
3348 /* compare index predicates */
3349 if (p_info->indpred_str &&
3350 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
3356 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
3357 Anum_pg_index_indpred,
3360 result = DirectFunctionCall2(pg_get_expr,
3365 if (strcmp(p_info->indpred_str,
3366 text_to_cstring(DatumGetTextP(result))) != 0)
3369 ReleaseSysCache(ht_idx);
3375 ReleaseSysCache(ht_idx);
3377 else if (p_info->expression_str || (info->indexprs != NIL))
3379 else if (p_info->indpred_str || (info->indpred != NIL))
3384 /* to log the candidate of index */
3385 if (debug_level > 0)
3387 appendStringInfoCharMacro(&buf, ' ');
3388 quote_value(&buf, indexname);
3396 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
3403 if (debug_level == 1)
3405 StringInfoData rel_buf;
3406 char *disprelname = "";
3409 * If this hint targetted the parent, use the real name of this
3410 * child. Otherwise use hint specification.
3412 if (using_parent_hint)
3413 disprelname = get_rel_name(rte->relid);
3415 disprelname = hint->relname;
3418 initStringInfo(&rel_buf);
3419 quote_value(&rel_buf, disprelname);
3422 (errmsg("available indexes for %s(%s):%s",
3427 pfree(rel_buf.data);
3432 * Return information of index definition.
3434 static ParentIndexInfo *
3435 get_parent_index_info(Oid indexoid, Oid relid)
3437 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
3438 Relation indexRelation;
3439 Form_pg_index index;
3443 indexRelation = index_open(indexoid, RowExclusiveLock);
3445 index = indexRelation->rd_index;
3447 p_info->indisunique = index->indisunique;
3448 p_info->method = indexRelation->rd_rel->relam;
3450 p_info->column_names = NIL;
3451 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3452 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
3453 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
3455 for (i = 0; i < index->indnatts; i++)
3457 attname = get_attname(relid, index->indkey.values[i]);
3458 p_info->column_names = lappend(p_info->column_names, attname);
3460 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
3461 p_info->opclass[i] = indexRelation->rd_opcintype[i];
3462 p_info->indoption[i] = indexRelation->rd_indoption[i];
3466 * to check to match the expression's parameter of index with child indexes
3468 p_info->expression_str = NULL;
3469 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
3475 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3476 Anum_pg_index_indexprs, &isnull);
3478 result = DirectFunctionCall2(pg_get_expr,
3480 ObjectIdGetDatum(relid));
3482 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
3486 * to check to match the predicate's parameter of index with child indexes
3488 p_info->indpred_str = NULL;
3489 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
3495 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
3496 Anum_pg_index_indpred, &isnull);
3498 result = DirectFunctionCall2(pg_get_expr,
3500 ObjectIdGetDatum(relid));
3502 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
3505 index_close(indexRelation, NoLock);
3511 * cancel hint enforcement
3514 reset_hint_enforcement()
3516 setup_scan_method_enforcement(NULL, current_hint_state);
3517 setup_parallel_plan_enforcement(NULL, current_hint_state);
3521 * Set planner guc parameters according to corresponding scan hints. Returns
3522 * bitmap of HintTypeBitmap. If shint or phint is not NULL, set used hint
3523 * there respectively.
3526 setup_hint_enforcement(PlannerInfo *root, RelOptInfo *rel,
3527 ScanMethodHint **rshint, ParallelHint **rphint)
3529 Index new_parent_relid = 0;
3531 ScanMethodHint *shint = NULL;
3532 ParallelHint *phint = NULL;
3533 bool inhparent = root->simple_rte_array[rel->relid]->inh;
3534 Oid relationObjectId = root->simple_rte_array[rel->relid]->relid;
3537 /* reset returns if requested */
3538 if (rshint != NULL) *rshint = NULL;
3539 if (rphint != NULL) *rphint = NULL;
3542 * We could register the parent relation of the following children here
3543 * when inhparent == true but inheritnce planner doesn't call this function
3544 * for parents. Since we cannot distinguish who called this function we
3545 * cannot do other than always seeking the parent regardless of who called
3550 if (debug_level > 1)
3551 ereport(pg_hint_plan_message_level,
3553 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3554 " skipping inh parent: relation=%u(%s), inhparent=%d,"
3555 " current_hint_state=%p, hint_inhibit_level=%d",
3556 qnostr, relationObjectId,
3557 get_rel_name(relationObjectId),
3558 inhparent, current_hint_state, hint_inhibit_level)));
3562 /* Find the parent for this relation other than the registered parent */
3563 foreach (l, root->append_rel_list)
3565 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3567 if (appinfo->child_relid == rel->relid)
3569 if (current_hint_state->parent_relid != appinfo->parent_relid)
3570 new_parent_relid = appinfo->parent_relid;
3577 /* This relation doesn't have a parent. Cancel current_hint_state. */
3578 current_hint_state->parent_relid = 0;
3579 current_hint_state->parent_scan_hint = NULL;
3580 current_hint_state->parent_parallel_hint = NULL;
3583 if (new_parent_relid > 0)
3586 * Here we found a new parent for the current relation. Scan continues
3587 * hint to other childrens of this parent so remember it * to avoid
3588 * hinthintredundant setup cost.
3590 current_hint_state->parent_relid = new_parent_relid;
3592 /* Find hints for the parent */
3593 current_hint_state->parent_scan_hint =
3594 find_scan_hint(root, current_hint_state->parent_relid);
3596 current_hint_state->parent_parallel_hint =
3597 find_parallel_hint(root, current_hint_state->parent_relid);
3600 * If hint is found for the parent, apply it for this child instead
3603 if (current_hint_state->parent_scan_hint)
3605 ScanMethodHint * pshint = current_hint_state->parent_scan_hint;
3607 pshint->base.state = HINT_STATE_USED;
3609 /* Apply index mask in the same manner to the parent. */
3610 if (pshint->indexnames)
3613 Relation parent_rel;
3616 root->simple_rte_array[current_hint_state->parent_relid]->relid;
3617 parent_rel = heap_open(parentrel_oid, NoLock);
3619 /* Search the parent relation for indexes match the hint spec */
3620 foreach(l, RelationGetIndexList(parent_rel))
3622 Oid indexoid = lfirst_oid(l);
3623 char *indexname = get_rel_name(indexoid);
3625 ParentIndexInfo *parent_index_info;
3627 foreach(lc, pshint->indexnames)
3629 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3636 get_parent_index_info(indexoid, parentrel_oid);
3637 current_hint_state->parent_index_infos =
3638 lappend(current_hint_state->parent_index_infos,
3641 heap_close(parent_rel, NoLock);
3646 shint = find_scan_hint(root, rel->relid);
3648 shint = current_hint_state->parent_scan_hint;
3652 bool using_parent_hint =
3653 (shint == current_hint_state->parent_scan_hint);
3655 ret |= HINT_BM_SCAN_METHOD;
3657 /* Setup scan enforcement environment */
3658 setup_scan_method_enforcement(shint, current_hint_state);
3660 /* restrict unwanted inexes */
3661 restrict_indexes(root, shint, rel, using_parent_hint);
3663 if (debug_level > 1)
3665 char *additional_message = "";
3667 if (shint == current_hint_state->parent_scan_hint)
3668 additional_message = " by parent hint";
3670 ereport(pg_hint_plan_message_level,
3672 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3673 " index deletion%s:"
3674 " relation=%u(%s), inhparent=%d, "
3675 "current_hint_state=%p,"
3676 " hint_inhibit_level=%d, scanmask=0x%x",
3677 qnostr, additional_message,
3679 get_rel_name(relationObjectId),
3680 inhparent, current_hint_state,
3682 shint->enforce_mask)));
3686 /* Do the same for parallel plan enforcement */
3687 phint = find_parallel_hint(root, rel->relid);
3689 phint = current_hint_state->parent_parallel_hint;
3691 setup_parallel_plan_enforcement(phint, current_hint_state);
3694 ret |= HINT_BM_PARALLEL;
3696 /* Nothing to apply. Reset the scan mask to intial state */
3697 if (!shint && ! phint)
3699 if (debug_level > 1)
3700 ereport(pg_hint_plan_message_level,
3701 (errhidestmt (true),
3702 errmsg ("pg_hint_plan%s: setup_hint_enforcement"
3704 " relation=%u(%s), inhparent=%d, current_hint=%p,"
3705 " hint_inhibit_level=%d, scanmask=0x%x",
3706 qnostr, relationObjectId,
3707 get_rel_name(relationObjectId),
3708 inhparent, current_hint_state, hint_inhibit_level,
3709 current_hint_state->init_scan_mask)));
3711 setup_scan_method_enforcement(NULL, current_hint_state);
3716 if (rshint != NULL) *rshint = shint;
3717 if (rphint != NULL) *rphint = phint;
3723 * Return index of relation which matches given aliasname, or 0 if not found.
3724 * If same aliasname was used multiple times in a query, return -1.
3727 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3733 for (i = 1; i < root->simple_rel_array_size; i++)
3737 if (root->simple_rel_array[i] == NULL)
3740 Assert(i == root->simple_rel_array[i]->relid);
3742 if (RelnameCmp(&aliasname,
3743 &root->simple_rte_array[i]->eref->aliasname) != 0)
3746 foreach(l, initial_rels)
3748 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3750 if (rel->reloptkind == RELOPT_BASEREL)
3752 if (rel->relid != i)
3757 Assert(rel->reloptkind == RELOPT_JOINREL);
3759 if (!bms_is_member(i, rel->relids))
3766 ("Relation name \"%s\" is ambiguous.",
3781 * Return join hint which matches given joinrelids.
3783 static JoinMethodHint *
3784 find_join_hint(Relids joinrelids)
3789 join_hint = current_hint_state->join_hint_level[bms_num_members(joinrelids)];
3791 foreach(l, join_hint)
3793 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3795 if (bms_equal(joinrelids, hint->joinrelids))
3803 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3804 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3806 OuterInnerRels *outer_rels;
3807 OuterInnerRels *inner_rels;
3808 Relids outer_relids;
3809 Relids inner_relids;
3811 JoinMethodHint *hint;
3813 if (outer_inner->relation != NULL)
3815 return bms_make_singleton(
3816 find_relid_aliasname(root, outer_inner->relation,
3818 leading_hint->base.hint_str));
3821 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3822 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3824 outer_relids = OuterInnerJoinCreate(outer_rels,
3830 inner_relids = OuterInnerJoinCreate(inner_rels,
3837 join_relids = bms_add_members(outer_relids, inner_relids);
3839 if (bms_num_members(join_relids) > nbaserel)
3843 * If we don't have join method hint, create new one for the
3844 * join combination with all join methods are enabled.
3846 hint = find_join_hint(join_relids);
3850 * Here relnames is not set, since Relids bitmap is sufficient to
3851 * control paths of this query afterward.
3853 hint = (JoinMethodHint *) JoinMethodHintCreate(
3854 leading_hint->base.hint_str,
3856 HINT_KEYWORD_LEADING);
3857 hint->base.state = HINT_STATE_USED;
3858 hint->nrels = bms_num_members(join_relids);
3859 hint->enforce_mask = ENABLE_ALL_JOIN;
3860 hint->joinrelids = bms_copy(join_relids);
3861 hint->inner_nrels = bms_num_members(inner_relids);
3862 hint->inner_joinrelids = bms_copy(inner_relids);
3864 hstate->join_hint_level[hint->nrels] =
3865 lappend(hstate->join_hint_level[hint->nrels], hint);
3869 hint->inner_nrels = bms_num_members(inner_relids);
3870 hint->inner_joinrelids = bms_copy(inner_relids);
3877 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3878 int nrels, char **relnames)
3881 Relids relids = NULL;
3885 for (j = 0; j < nrels; j++)
3887 relname = relnames[j];
3889 relid = find_relid_aliasname(root, relname, initial_rels,
3893 base->state = HINT_STATE_ERROR;
3896 * the aliasname is not found(relid == 0) or same aliasname was used
3897 * multiple times in a query(relid == -1)
3904 if (bms_is_member(relid, relids))
3906 hint_ereport(base->hint_str,
3907 ("Relation name \"%s\" is duplicated.", relname));
3908 base->state = HINT_STATE_ERROR;
3912 relids = bms_add_member(relids, relid);
3917 * Transform join method hint into handy form.
3919 * - create bitmap of relids from alias names, to make it easier to check
3920 * whether a join path matches a join method hint.
3921 * - add join method hints which are necessary to enforce join order
3922 * specified by Leading hint
3925 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3926 List *initial_rels, JoinMethodHint **join_method_hints)
3934 LeadingHint *lhint = NULL;
3937 * Create bitmap of relids from alias names for each join method hint.
3938 * Bitmaps are more handy than strings in join searching.
3940 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3942 JoinMethodHint *hint = hstate->join_hints[i];
3944 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3947 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3948 initial_rels, hint->nrels, hint->relnames);
3950 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3953 hstate->join_hint_level[hint->nrels] =
3954 lappend(hstate->join_hint_level[hint->nrels], hint);
3958 * Create bitmap of relids from alias names for each rows hint.
3959 * Bitmaps are more handy than strings in join searching.
3961 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3963 RowsHint *hint = hstate->rows_hints[i];
3965 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3968 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3969 initial_rels, hint->nrels, hint->relnames);
3972 /* Do nothing if no Leading hint was supplied. */
3973 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3977 * Decide whether to use Leading hint
3979 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3981 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3984 if (leading_hint->base.state == HINT_STATE_ERROR)
3990 foreach(l, leading_hint->relations)
3992 relname = (char *)lfirst(l);;
3994 relid = find_relid_aliasname(root, relname, initial_rels,
3995 leading_hint->base.hint_str);
3997 leading_hint->base.state = HINT_STATE_ERROR;
4002 if (bms_is_member(relid, relids))
4004 hint_ereport(leading_hint->base.hint_str,
4005 ("Relation name \"%s\" is duplicated.", relname));
4006 leading_hint->base.state = HINT_STATE_ERROR;
4010 relids = bms_add_member(relids, relid);
4013 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
4018 hint_ereport(lhint->base.hint_str,
4019 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
4020 lhint->base.state = HINT_STATE_DUPLICATION;
4022 leading_hint->base.state = HINT_STATE_USED;
4023 lhint = leading_hint;
4026 /* check to exist Leading hint marked with 'used'. */
4031 * We need join method hints which fit specified join order in every join
4032 * level. For example, Leading(A B C) virtually requires following join
4033 * method hints, if no join method hint supplied:
4035 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
4036 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
4038 * If we already have join method hint which fits specified join order in
4039 * that join level, we leave it as-is and don't add new hints.
4043 if (lhint->outer_inner == NULL)
4045 foreach(l, lhint->relations)
4047 JoinMethodHint *hint;
4049 relname = (char *)lfirst(l);
4052 * Find relid of the relation which has given name. If we have the
4053 * name given in Leading hint multiple times in the join, nothing to
4056 relid = find_relid_aliasname(root, relname, initial_rels,
4059 /* Create bitmap of relids for current join level. */
4060 joinrelids = bms_add_member(joinrelids, relid);
4063 /* We never have join method hint for single relation. */
4068 * If we don't have join method hint, create new one for the
4069 * join combination with all join methods are enabled.
4071 hint = find_join_hint(joinrelids);
4075 * Here relnames is not set, since Relids bitmap is sufficient
4076 * to control paths of this query afterward.
4078 hint = (JoinMethodHint *) JoinMethodHintCreate(
4079 lhint->base.hint_str,
4081 HINT_KEYWORD_LEADING);
4082 hint->base.state = HINT_STATE_USED;
4083 hint->nrels = njoinrels;
4084 hint->enforce_mask = ENABLE_ALL_JOIN;
4085 hint->joinrelids = bms_copy(joinrelids);
4088 join_method_hints[njoinrels] = hint;
4090 if (njoinrels >= nbaserel)
4093 bms_free(joinrelids);
4099 * Delete all join hints which have different combination from Leading
4102 for (i = 2; i <= njoinrels; i++)
4104 list_free(hstate->join_hint_level[i]);
4106 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
4111 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
4118 njoinrels = bms_num_members(joinrelids);
4119 Assert(njoinrels >= 2);
4122 * Delete all join hints which have different combination from Leading
4125 for (i = 2;i <= njoinrels; i++)
4127 if (hstate->join_hint_level[i] != NIL)
4129 ListCell *prev = NULL;
4130 ListCell *next = NULL;
4131 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
4134 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
4138 if (hint->inner_nrels == 0 &&
4139 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
4140 bms_equal(bms_union(hint->joinrelids, joinrelids),
4143 hstate->join_hint_level[i] =
4144 list_delete_cell(hstate->join_hint_level[i], l,
4153 bms_free(joinrelids);
4156 if (hint_state_enabled(lhint))
4158 set_join_config_options(DISABLE_ALL_JOIN, current_hint_state->context);
4165 * wrapper of make_join_rel()
4167 * call make_join_rel() after changing enable_* parameters according to given
4171 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
4174 JoinMethodHint *hint;
4178 joinrelids = bms_union(rel1->relids, rel2->relids);
4179 hint = find_join_hint(joinrelids);
4180 bms_free(joinrelids);
4183 return pg_hint_plan_make_join_rel(root, rel1, rel2);
4185 if (hint->inner_nrels == 0)
4187 save_nestlevel = NewGUCNestLevel();
4189 set_join_config_options(hint->enforce_mask,
4190 current_hint_state->context);
4192 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4193 hint->base.state = HINT_STATE_USED;
4196 * Restore the GUC variables we set above.
4198 AtEOXact_GUC(true, save_nestlevel);
4201 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
4210 add_paths_to_joinrel_wrapper(PlannerInfo *root,
4211 RelOptInfo *joinrel,
4212 RelOptInfo *outerrel,
4213 RelOptInfo *innerrel,
4215 SpecialJoinInfo *sjinfo,
4219 JoinMethodHint *join_hint;
4222 joinrelids = bms_union(outerrel->relids, innerrel->relids);
4223 join_hint = find_join_hint(joinrelids);
4224 bms_free(joinrelids);
4226 if (join_hint && join_hint->inner_nrels != 0)
4228 save_nestlevel = NewGUCNestLevel();
4230 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
4233 set_join_config_options(join_hint->enforce_mask,
4234 current_hint_state->context);
4236 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4237 sjinfo, restrictlist);
4238 join_hint->base.state = HINT_STATE_USED;
4242 set_join_config_options(DISABLE_ALL_JOIN,
4243 current_hint_state->context);
4244 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4245 sjinfo, restrictlist);
4249 * Restore the GUC variables we set above.
4251 AtEOXact_GUC(true, save_nestlevel);
4254 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
4255 sjinfo, restrictlist);
4259 get_num_baserels(List *initial_rels)
4264 foreach(l, initial_rels)
4266 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
4268 if (rel->reloptkind == RELOPT_BASEREL)
4270 else if (rel->reloptkind ==RELOPT_JOINREL)
4271 nbaserel+= bms_num_members(rel->relids);
4274 /* other values not expected here */
4275 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
4283 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
4286 JoinMethodHint **join_method_hints;
4290 bool leading_hint_enable;
4293 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
4294 * valid hint is supplied or current nesting depth is nesting depth of SPI
4297 if (!current_hint_state || hint_inhibit_level > 0)
4299 if (prev_join_search)
4300 return (*prev_join_search) (root, levels_needed, initial_rels);
4301 else if (enable_geqo && levels_needed >= geqo_threshold)
4302 return geqo(root, levels_needed, initial_rels);
4304 return standard_join_search(root, levels_needed, initial_rels);
4308 * In the case using GEQO, only scan method hints and Set hints have
4309 * effect. Join method and join order is not controllable by hints.
4311 if (enable_geqo && levels_needed >= geqo_threshold)
4312 return geqo(root, levels_needed, initial_rels);
4314 nbaserel = get_num_baserels(initial_rels);
4315 current_hint_state->join_hint_level =
4316 palloc0(sizeof(List *) * (nbaserel + 1));
4317 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
4319 leading_hint_enable = transform_join_hints(current_hint_state,
4321 initial_rels, join_method_hints);
4323 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
4325 for (i = 2; i <= nbaserel; i++)
4327 list_free(current_hint_state->join_hint_level[i]);
4329 /* free Leading hint only */
4330 if (join_method_hints[i] != NULL &&
4331 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
4332 JoinMethodHintDelete(join_method_hints[i]);
4334 pfree(current_hint_state->join_hint_level);
4335 pfree(join_method_hints);
4337 if (leading_hint_enable)
4338 set_join_config_options(current_hint_state->init_join_mask,
4339 current_hint_state->context);
4345 * Force number of wokers if instructed by hint
4348 pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
4349 Index rti, RangeTblEntry *rte)
4351 ParallelHint *phint;
4355 /* call the previous hook */
4356 if (prev_set_rel_pathlist)
4357 prev_set_rel_pathlist(root, rel, rti, rte);
4359 /* Nothing to do if no hint available */
4360 if (current_hint_state == NULL)
4363 /* Don't touch dummy rels. */
4364 if (IS_DUMMY_REL(rel))
4368 * We can accept only plain relations, foreign tables and table saples are
4369 * also unacceptable. See set_rel_pathlist.
4371 if (rel->rtekind != RTE_RELATION ||
4372 rte->relkind == RELKIND_FOREIGN_TABLE ||
4373 rte->tablesample != NULL)
4376 /* We cannot handle if this requires an outer */
4377 if (rel->lateral_relids)
4380 /* Return if this relation gets no enfocement */
4381 if ((found_hints = setup_hint_enforcement(root, rel, NULL, &phint)) == 0)
4384 /* Here, we regenerate paths with the current hint restriction */
4386 if (found_hints & HINT_BM_SCAN_METHOD)
4389 * With scan hints, we regenerate paths for this relation from the
4390 * first under the restricion.
4392 list_free_deep(rel->pathlist);
4393 rel->pathlist = NIL;
4395 set_plain_rel_pathlist(root, rel, rte);
4398 if (found_hints & HINT_BM_PARALLEL)
4402 /* the partial_pathlist may be for different parameters, discard it */
4403 if (rel->partial_pathlist)
4405 list_free_deep(rel->partial_pathlist);
4406 rel->partial_pathlist = NIL;
4409 /* also remove gather path */
4412 ListCell *cell, *prev = NULL;
4414 foreach (cell, rel->pathlist)
4416 Path *path = (Path *) lfirst(cell);
4418 if (IsA(path, GatherPath))
4419 rel->pathlist = list_delete_cell(rel->pathlist,
4426 /* then generate new paths if needed */
4427 if (phint->nworkers > 0)
4429 /* Lower the priorities of non-parallel paths */
4430 foreach (l, rel->pathlist)
4432 Path *path = (Path *) lfirst(l);
4434 if (path->startup_cost < disable_cost)
4436 path->startup_cost += disable_cost;
4437 path->total_cost += disable_cost;
4442 * generate partial paths with enforcement, this is affected by
4443 * scan method enforcement. Specifically, the cost of this partial
4444 * seqscan path will be disabled_cost if seqscan is inhibited by
4445 * hint or GUC parameters.
4447 Assert (rel->partial_pathlist == NIL);
4448 create_plain_partial_paths(root, rel);
4450 /* enforce number of workers if requested */
4451 if (phint->force_parallel)
4453 foreach (l, rel->partial_pathlist)
4455 Path *ppath = (Path *) lfirst(l);
4457 ppath->parallel_workers = phint->nworkers;
4461 /* Generate gather paths for base rels */
4462 if (rel->reloptkind == RELOPT_BASEREL)
4463 generate_gather_paths(root, rel);
4467 reset_hint_enforcement();
4472 * Build access paths for a base relation
4474 * This function was copied and edited from set_rel_pathlist() in
4475 * src/backend/optimizer/path/allpaths.c in order not to copy other static
4476 * functions not required here.
4479 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
4480 Index rti, RangeTblEntry *rte)
4482 if (IS_DUMMY_REL(rel))
4484 /* We already proved the relation empty, so nothing more to do */
4488 /* It's an "append relation", process accordingly */
4489 set_append_rel_pathlist(root, rel, rti, rte);
4493 if (rel->rtekind == RTE_RELATION)
4495 if (rte->relkind == RELKIND_RELATION)
4497 if(rte->tablesample != NULL)
4498 elog(ERROR, "sampled relation is not supported");
4500 /* Plain relation */
4501 set_plain_rel_pathlist(root, rel, rte);
4504 elog(ERROR, "unexpected relkind: %c", rte->relkind);
4507 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
4511 * Allow a plugin to editorialize on the set of Paths for this base
4512 * relation. It could add new paths (such as CustomPaths) by calling
4513 * add_path(), or delete or modify paths added by the core code.
4515 if (set_rel_pathlist_hook)
4516 (*set_rel_pathlist_hook) (root, rel, rti, rte);
4518 /* Now find the cheapest of the paths for this rel */
4523 * stmt_beg callback is called when each query in PL/pgSQL function is about
4524 * to be executed. At that timing, we save query string in the global variable
4525 * plpgsql_query_string to use it in planner hook. It's safe to use one global
4526 * variable for the purpose, because its content is only necessary until
4527 * planner hook is called for the query, so recursive PL/pgSQL function calls
4528 * don't harm this mechanism.
4531 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4533 plpgsql_recurse_level++;
4537 * stmt_end callback is called then each query in PL/pgSQL function has
4538 * finished. At that timing, we clear plpgsql_query_string to tell planner
4539 * hook that next call is not for a query written in PL/pgSQL block.
4542 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
4544 plpgsql_recurse_level--;
4547 void plpgsql_query_erase_callback(ResourceReleasePhase phase,
4552 if (phase != RESOURCE_RELEASE_AFTER_LOCKS)
4554 /* Cancel plpgsql nest level*/
4555 plpgsql_recurse_level = 0;
4558 #define standard_join_search pg_hint_plan_standard_join_search
4559 #define join_search_one_level pg_hint_plan_join_search_one_level
4560 #define make_join_rel make_join_rel_wrapper
4563 #undef make_join_rel
4564 #define make_join_rel pg_hint_plan_make_join_rel
4565 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
4566 #include "make_join_rel.c"
4568 #include "pg_stat_statements.c"