1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012-2014, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
9 *-------------------------------------------------------------------------
12 #include "catalog/pg_collation.h"
13 #include "catalog/pg_index.h"
14 #include "commands/prepare.h"
15 #include "mb/pg_wchar.h"
16 #include "miscadmin.h"
17 #include "nodes/nodeFuncs.h"
18 #include "optimizer/clauses.h"
19 #include "optimizer/cost.h"
20 #include "optimizer/geqo.h"
21 #include "optimizer/joininfo.h"
22 #include "optimizer/pathnode.h"
23 #include "optimizer/paths.h"
24 #include "optimizer/plancat.h"
25 #include "optimizer/planner.h"
26 #include "optimizer/prep.h"
27 #include "optimizer/restrictinfo.h"
28 #include "parser/scansup.h"
29 #include "tcop/utility.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/memutils.h"
33 #include "utils/rel.h"
34 #include "utils/syscache.h"
36 #include "catalog/pg_class.h"
38 #include "executor/spi.h"
39 #include "catalog/pg_type.h"
42 * We have our own header file "plpgsql-9.1", which is necessary to support
43 * hints for queries in PL/pgSQL blocks, in pg_hint_plan source package,
44 * because PostgreSQL 9.1 doesn't provide the header file as a part of
45 * installation. This header file is a copy of src/pl/plpgsql/src/plpgsql.h in
46 * PostgreSQL 9.1.9 source tree,
48 * On the other hand, 9.2 installation provides that header file for external
49 * modules, so we include the header in ordinary place.
53 /* partially copied from pg_stat_statements */
54 #include "normalize_query.h"
56 #ifdef PG_MODULE_MAGIC
60 #define BLOCK_COMMENT_START "/*"
61 #define BLOCK_COMMENT_END "*/"
62 #define HINT_COMMENT_KEYWORD "+"
63 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
64 #define HINT_END BLOCK_COMMENT_END
67 #define HINT_SEQSCAN "SeqScan"
68 #define HINT_INDEXSCAN "IndexScan"
69 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
70 #define HINT_BITMAPSCAN "BitmapScan"
71 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
72 #define HINT_TIDSCAN "TidScan"
73 #define HINT_NOSEQSCAN "NoSeqScan"
74 #define HINT_NOINDEXSCAN "NoIndexScan"
75 #define HINT_NOBITMAPSCAN "NoBitmapScan"
76 #define HINT_NOTIDSCAN "NoTidScan"
77 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
78 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
79 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
80 #define HINT_NESTLOOP "NestLoop"
81 #define HINT_MERGEJOIN "MergeJoin"
82 #define HINT_HASHJOIN "HashJoin"
83 #define HINT_NONESTLOOP "NoNestLoop"
84 #define HINT_NOMERGEJOIN "NoMergeJoin"
85 #define HINT_NOHASHJOIN "NoHashJoin"
86 #define HINT_LEADING "Leading"
87 #define HINT_SET "Set"
88 #define HINT_ROWS "Rows"
90 #define HINT_ARRAY_DEFAULT_INITSIZE 8
92 #define hint_ereport(str, detail) \
93 ereport(pg_hint_plan_parse_messages, \
94 (errmsg("hint syntax error at or near \"%s\"", (str)), \
97 #define skip_space(str) \
98 while (isspace(*str)) \
103 ENABLE_SEQSCAN = 0x01,
104 ENABLE_INDEXSCAN = 0x02,
105 ENABLE_BITMAPSCAN = 0x04,
106 ENABLE_TIDSCAN = 0x08,
107 ENABLE_INDEXONLYSCAN = 0x10
112 ENABLE_NESTLOOP = 0x01,
113 ENABLE_MERGEJOIN = 0x02,
114 ENABLE_HASHJOIN = 0x04
117 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
118 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
119 ENABLE_INDEXONLYSCAN)
120 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
121 #define DISABLE_ALL_SCAN 0
122 #define DISABLE_ALL_JOIN 0
124 /* hint keyword of enum type*/
125 typedef enum HintKeyword
127 HINT_KEYWORD_SEQSCAN,
128 HINT_KEYWORD_INDEXSCAN,
129 HINT_KEYWORD_INDEXSCANREGEXP,
130 HINT_KEYWORD_BITMAPSCAN,
131 HINT_KEYWORD_BITMAPSCANREGEXP,
132 HINT_KEYWORD_TIDSCAN,
133 HINT_KEYWORD_NOSEQSCAN,
134 HINT_KEYWORD_NOINDEXSCAN,
135 HINT_KEYWORD_NOBITMAPSCAN,
136 HINT_KEYWORD_NOTIDSCAN,
137 HINT_KEYWORD_INDEXONLYSCAN,
138 HINT_KEYWORD_INDEXONLYSCANREGEXP,
139 HINT_KEYWORD_NOINDEXONLYSCAN,
140 HINT_KEYWORD_NESTLOOP,
141 HINT_KEYWORD_MERGEJOIN,
142 HINT_KEYWORD_HASHJOIN,
143 HINT_KEYWORD_NONESTLOOP,
144 HINT_KEYWORD_NOMERGEJOIN,
145 HINT_KEYWORD_NOHASHJOIN,
146 HINT_KEYWORD_LEADING,
149 HINT_KEYWORD_UNRECOGNIZED
152 typedef struct Hint Hint;
153 typedef struct HintState HintState;
155 typedef Hint *(*HintCreateFunction) (const char *hint_str,
157 HintKeyword hint_keyword);
158 typedef void (*HintDeleteFunction) (Hint *hint);
159 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
160 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
161 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
162 Query *parse, const char *str);
165 #define NUM_HINT_TYPE 5
166 typedef enum HintType
168 HINT_TYPE_SCAN_METHOD,
169 HINT_TYPE_JOIN_METHOD,
175 static const char *HintTypeName[] = {
184 typedef enum HintStatus
186 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
187 HINT_STATE_USED, /* hint is used */
188 HINT_STATE_DUPLICATION, /* specified hint duplication */
189 HINT_STATE_ERROR /* execute error (parse error does not include
193 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
194 (hint)->base.state == HINT_STATE_USED)
196 /* common data for all hints. */
199 const char *hint_str; /* must not do pfree */
200 const char *keyword; /* must not do pfree */
201 HintKeyword hint_keyword;
204 HintDeleteFunction delete_func;
205 HintDescFunction desc_func;
206 HintCmpFunction cmp_func;
207 HintParseFunction parse_func;
210 /* scan method hints */
211 typedef struct ScanMethodHint
217 unsigned char enforce_mask;
220 typedef struct ParentIndexInfo
225 char *expression_str;
232 /* join method hints */
233 typedef struct JoinMethodHint
239 unsigned char enforce_mask;
241 Relids inner_joinrelids;
244 /* join order hints */
245 typedef struct OuterInnerRels
248 List *outer_inner_pair;
251 typedef struct LeadingHint
254 List *relations; /* relation names specified in Leading hint */
255 OuterInnerRels *outer_inner;
258 /* change a run-time parameter hints */
259 typedef struct SetHint
262 char *name; /* name of variable */
268 typedef enum RowsValueType {
269 RVT_ABSOLUTE, /* Rows(... #1000) */
270 RVT_ADD, /* Rows(... +1000) */
271 RVT_SUB, /* Rows(... -1000) */
272 RVT_MULTI, /* Rows(... *1.2) */
274 typedef struct RowsHint
281 Relids inner_joinrelids;
283 RowsValueType value_type;
288 * Describes a context of hint processing.
292 char *hint_str; /* original hint string */
295 int nall_hints; /* # of valid all hints */
296 int max_all_hints; /* # of slots for all hints */
297 Hint **all_hints; /* parsed all hints */
299 /* # of each hints */
300 int num_hints[NUM_HINT_TYPE];
302 /* for scan method hints */
303 ScanMethodHint **scan_hints; /* parsed scan hints */
304 int init_scan_mask; /* initial value scan parameter */
305 Index parent_relid; /* inherit parent table relid */
306 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
307 List *parent_index_infos; /* information of inherit parent table's
310 /* for join method hints */
311 JoinMethodHint **join_hints; /* parsed join hints */
312 int init_join_mask; /* initial value join parameter */
313 List **join_hint_level;
315 /* for Leading hint */
316 LeadingHint **leading_hint; /* parsed Leading hints */
319 SetHint **set_hints; /* parsed Set hints */
320 GucContext context; /* which GUC parameters can we set? */
323 RowsHint **rows_hints; /* parsed Rows hints */
327 * Describes a hint parser module which is bound with particular hint keyword.
329 typedef struct HintParser
332 HintCreateFunction create_func;
333 HintKeyword hint_keyword;
336 /* Module callbacks */
340 static void push_hint(HintState *hstate);
341 static void pop_hint(void);
343 static void pg_hint_plan_ProcessUtility(Node *parsetree,
344 const char *queryString,
345 ParamListInfo params, bool isTopLevel,
347 char *completionTag);
348 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
349 ParamListInfo boundParams);
350 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
351 Oid relationObjectId,
352 bool inhparent, RelOptInfo *rel);
353 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
357 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
358 HintKeyword hint_keyword);
359 static void ScanMethodHintDelete(ScanMethodHint *hint);
360 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
361 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
362 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
363 Query *parse, const char *str);
364 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
365 HintKeyword hint_keyword);
366 static void JoinMethodHintDelete(JoinMethodHint *hint);
367 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
368 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
369 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
370 Query *parse, const char *str);
371 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
372 HintKeyword hint_keyword);
373 static void LeadingHintDelete(LeadingHint *hint);
374 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
375 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
376 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
377 Query *parse, const char *str);
378 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
379 HintKeyword hint_keyword);
380 static void SetHintDelete(SetHint *hint);
381 static void SetHintDesc(SetHint *hint, StringInfo buf);
382 static int SetHintCmp(const SetHint *a, const SetHint *b);
383 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
385 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
386 HintKeyword hint_keyword);
387 static void RowsHintDelete(RowsHint *hint);
388 static void RowsHintDesc(RowsHint *hint, StringInfo buf);
389 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
390 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
391 Query *parse, const char *str);
392 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
393 HintKeyword hint_keyword);
395 static void quote_value(StringInfo buf, const char *value);
397 static const char *parse_quoted_value(const char *str, char **word,
400 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
403 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
404 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
405 ListCell *other_rels);
406 static void make_rels_by_clauseless_joins(PlannerInfo *root,
408 ListCell *other_rels);
409 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
410 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
411 Index rti, RangeTblEntry *rte);
412 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
413 List *live_childrels,
414 List *all_child_pathkeys);
415 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
417 Relids required_outer);
418 static List *accumulate_append_subpath(List *subpaths, Path *path);
419 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
422 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
424 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
428 static bool pg_hint_plan_enable_hint = true;
429 static bool pg_hint_plan_debug_print = false;
430 static int pg_hint_plan_parse_messages = INFO;
431 /* Default is off, to keep backward compatibility. */
432 static bool pg_hint_plan_enable_hint_table = false;
434 static const struct config_enum_entry parse_messages_level_options[] = {
435 {"debug", DEBUG2, true},
436 {"debug5", DEBUG5, false},
437 {"debug4", DEBUG4, false},
438 {"debug3", DEBUG3, false},
439 {"debug2", DEBUG2, false},
440 {"debug1", DEBUG1, false},
442 {"info", INFO, false},
443 {"notice", NOTICE, false},
444 {"warning", WARNING, false},
445 {"error", ERROR, false},
447 * {"fatal", FATAL, true},
448 * {"panic", PANIC, true},
453 /* Saved hook values in case of unload */
454 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
455 static planner_hook_type prev_planner = NULL;
456 static get_relation_info_hook_type prev_get_relation_info = NULL;
457 static join_search_hook_type prev_join_search = NULL;
459 /* Hold reference to currently active hint */
460 static HintState *current_hint = NULL;
463 * List of hint contexts. We treat the head of the list as the Top of the
464 * context stack, so current_hint always points the first element of this list.
466 static List *HintStateStack = NIL;
469 * Holds statement name during executing EXECUTE command. NULL for other
472 static char *stmt_name = NULL;
474 static const HintParser parsers[] = {
475 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
476 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
477 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
478 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
479 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
480 HINT_KEYWORD_BITMAPSCANREGEXP},
481 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
482 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
483 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
484 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
485 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
486 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
487 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
488 HINT_KEYWORD_INDEXONLYSCANREGEXP},
489 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
490 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
491 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
492 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
493 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
494 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
495 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
496 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
497 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
498 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
499 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
503 * PL/pgSQL plugin for retrieving string representation of each query during
504 * function execution.
506 const char *plpgsql_query_string = NULL;
507 PLpgSQL_plugin plugin_funcs = {
511 pg_hint_plan_plpgsql_stmt_beg,
512 pg_hint_plan_plpgsql_stmt_end,
517 /* Current nesting depth of SPI calls, used to prevent recursive calls */
518 static int nested_level = 0;
521 * Module load callbacks
526 PLpgSQL_plugin **var_ptr;
528 /* Define custom GUC variables. */
529 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
530 "Force planner to use plans specified in the hint comment preceding to the query.",
532 &pg_hint_plan_enable_hint,
540 DefineCustomBoolVariable("pg_hint_plan.debug_print",
541 "Logs results of hint parsing.",
543 &pg_hint_plan_debug_print,
551 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
552 "Message level of parse errors.",
554 &pg_hint_plan_parse_messages,
556 parse_messages_level_options,
563 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
564 "Force planner to not get hint by using table lookups.",
566 &pg_hint_plan_enable_hint_table,
575 prev_ProcessUtility = ProcessUtility_hook;
576 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
577 prev_planner = planner_hook;
578 planner_hook = pg_hint_plan_planner;
579 prev_get_relation_info = get_relation_info_hook;
580 get_relation_info_hook = pg_hint_plan_get_relation_info;
581 prev_join_search = join_search_hook;
582 join_search_hook = pg_hint_plan_join_search;
584 /* setup PL/pgSQL plugin hook */
585 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
586 *var_ptr = &plugin_funcs;
590 * Module unload callback
596 PLpgSQL_plugin **var_ptr;
598 /* Uninstall hooks. */
599 ProcessUtility_hook = prev_ProcessUtility;
600 planner_hook = prev_planner;
601 get_relation_info_hook = prev_get_relation_info;
602 join_search_hook = prev_join_search;
604 /* uninstall PL/pgSQL plugin hook */
605 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
610 * create and delete functions the hint object
614 ScanMethodHintCreate(const char *hint_str, const char *keyword,
615 HintKeyword hint_keyword)
617 ScanMethodHint *hint;
619 hint = palloc(sizeof(ScanMethodHint));
620 hint->base.hint_str = hint_str;
621 hint->base.keyword = keyword;
622 hint->base.hint_keyword = hint_keyword;
623 hint->base.type = HINT_TYPE_SCAN_METHOD;
624 hint->base.state = HINT_STATE_NOTUSED;
625 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
626 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
627 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
628 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
629 hint->relname = NULL;
630 hint->indexnames = NIL;
631 hint->regexp = false;
632 hint->enforce_mask = 0;
634 return (Hint *) hint;
638 ScanMethodHintDelete(ScanMethodHint *hint)
644 pfree(hint->relname);
645 list_free_deep(hint->indexnames);
650 JoinMethodHintCreate(const char *hint_str, const char *keyword,
651 HintKeyword hint_keyword)
653 JoinMethodHint *hint;
655 hint = palloc(sizeof(JoinMethodHint));
656 hint->base.hint_str = hint_str;
657 hint->base.keyword = keyword;
658 hint->base.hint_keyword = hint_keyword;
659 hint->base.type = HINT_TYPE_JOIN_METHOD;
660 hint->base.state = HINT_STATE_NOTUSED;
661 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
662 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
663 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
664 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
666 hint->inner_nrels = 0;
667 hint->relnames = NULL;
668 hint->enforce_mask = 0;
669 hint->joinrelids = NULL;
670 hint->inner_joinrelids = NULL;
672 return (Hint *) hint;
676 JoinMethodHintDelete(JoinMethodHint *hint)
685 for (i = 0; i < hint->nrels; i++)
686 pfree(hint->relnames[i]);
687 pfree(hint->relnames);
690 bms_free(hint->joinrelids);
691 bms_free(hint->inner_joinrelids);
696 LeadingHintCreate(const char *hint_str, const char *keyword,
697 HintKeyword hint_keyword)
701 hint = palloc(sizeof(LeadingHint));
702 hint->base.hint_str = hint_str;
703 hint->base.keyword = keyword;
704 hint->base.hint_keyword = hint_keyword;
705 hint->base.type = HINT_TYPE_LEADING;
706 hint->base.state = HINT_STATE_NOTUSED;
707 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
708 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
709 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
710 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
711 hint->relations = NIL;
712 hint->outer_inner = NULL;
714 return (Hint *) hint;
718 LeadingHintDelete(LeadingHint *hint)
723 list_free_deep(hint->relations);
724 if (hint->outer_inner)
725 pfree(hint->outer_inner);
730 SetHintCreate(const char *hint_str, const char *keyword,
731 HintKeyword hint_keyword)
735 hint = palloc(sizeof(SetHint));
736 hint->base.hint_str = hint_str;
737 hint->base.keyword = keyword;
738 hint->base.hint_keyword = hint_keyword;
739 hint->base.type = HINT_TYPE_SET;
740 hint->base.state = HINT_STATE_NOTUSED;
741 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
742 hint->base.desc_func = (HintDescFunction) SetHintDesc;
743 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
744 hint->base.parse_func = (HintParseFunction) SetHintParse;
749 return (Hint *) hint;
753 SetHintDelete(SetHint *hint)
763 list_free(hint->words);
768 RowsHintCreate(const char *hint_str, const char *keyword,
769 HintKeyword hint_keyword)
773 hint = palloc(sizeof(RowsHint));
774 hint->base.hint_str = hint_str;
775 hint->base.keyword = keyword;
776 hint->base.hint_keyword = hint_keyword;
777 hint->base.type = HINT_TYPE_ROWS;
778 hint->base.state = HINT_STATE_NOTUSED;
779 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
780 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
781 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
782 hint->base.parse_func = (HintParseFunction) RowsHintParse;
784 hint->inner_nrels = 0;
785 hint->relnames = NULL;
786 hint->joinrelids = NULL;
787 hint->inner_joinrelids = NULL;
788 hint->rows_str = NULL;
789 hint->value_type = RVT_ABSOLUTE;
792 return (Hint *) hint;
796 RowsHintDelete(RowsHint *hint)
805 for (i = 0; i < hint->nrels; i++)
806 pfree(hint->relnames[i]);
807 pfree(hint->relnames);
810 bms_free(hint->joinrelids);
811 bms_free(hint->inner_joinrelids);
816 HintStateCreate(void)
820 hstate = palloc(sizeof(HintState));
821 hstate->hint_str = NULL;
822 hstate->nall_hints = 0;
823 hstate->max_all_hints = 0;
824 hstate->all_hints = NULL;
825 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
826 hstate->scan_hints = NULL;
827 hstate->init_scan_mask = 0;
828 hstate->parent_relid = 0;
829 hstate->parent_hint = NULL;
830 hstate->parent_index_infos = NIL;
831 hstate->join_hints = NULL;
832 hstate->init_join_mask = 0;
833 hstate->join_hint_level = NULL;
834 hstate->leading_hint = NULL;
835 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
836 hstate->set_hints = NULL;
837 hstate->rows_hints = NULL;
843 HintStateDelete(HintState *hstate)
850 if (hstate->hint_str)
851 pfree(hstate->hint_str);
853 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
854 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
855 if (hstate->all_hints)
856 pfree(hstate->all_hints);
857 if (hstate->parent_index_infos)
858 list_free(hstate->parent_index_infos);
862 * Copy given value into buf, with quoting with '"' if necessary.
865 quote_value(StringInfo buf, const char *value)
867 bool need_quote = false;
870 for (str = value; *str != '\0'; str++)
872 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
875 appendStringInfoCharMacro(buf, '"');
880 for (str = value; *str != '\0'; str++)
883 appendStringInfoCharMacro(buf, '"');
885 appendStringInfoCharMacro(buf, *str);
889 appendStringInfoCharMacro(buf, '"');
893 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
897 appendStringInfo(buf, "%s(", hint->base.keyword);
898 if (hint->relname != NULL)
900 quote_value(buf, hint->relname);
901 foreach(l, hint->indexnames)
903 appendStringInfoCharMacro(buf, ' ');
904 quote_value(buf, (char *) lfirst(l));
907 appendStringInfoString(buf, ")\n");
911 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
915 appendStringInfo(buf, "%s(", hint->base.keyword);
916 if (hint->relnames != NULL)
918 quote_value(buf, hint->relnames[0]);
919 for (i = 1; i < hint->nrels; i++)
921 appendStringInfoCharMacro(buf, ' ');
922 quote_value(buf, hint->relnames[i]);
925 appendStringInfoString(buf, ")\n");
930 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
932 if (outer_inner->relation == NULL)
939 appendStringInfoCharMacro(buf, '(');
940 foreach(l, outer_inner->outer_inner_pair)
945 appendStringInfoCharMacro(buf, ' ');
947 OuterInnerDesc(lfirst(l), buf);
950 appendStringInfoCharMacro(buf, ')');
953 quote_value(buf, outer_inner->relation);
957 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
959 appendStringInfo(buf, "%s(", HINT_LEADING);
960 if (hint->outer_inner == NULL)
967 foreach(l, hint->relations)
972 appendStringInfoCharMacro(buf, ' ');
974 quote_value(buf, (char *) lfirst(l));
978 OuterInnerDesc(hint->outer_inner, buf);
980 appendStringInfoString(buf, ")\n");
984 SetHintDesc(SetHint *hint, StringInfo buf)
986 bool is_first = true;
989 appendStringInfo(buf, "%s(", HINT_SET);
990 foreach(l, hint->words)
995 appendStringInfoCharMacro(buf, ' ');
997 quote_value(buf, (char *) lfirst(l));
999 appendStringInfo(buf, ")\n");
1003 RowsHintDesc(RowsHint *hint, StringInfo buf)
1007 appendStringInfo(buf, "%s(", hint->base.keyword);
1008 if (hint->relnames != NULL)
1010 quote_value(buf, hint->relnames[0]);
1011 for (i = 1; i < hint->nrels; i++)
1013 appendStringInfoCharMacro(buf, ' ');
1014 quote_value(buf, hint->relnames[i]);
1017 appendStringInfo(buf, " %s", hint->rows_str);
1018 appendStringInfoString(buf, ")\n");
1023 * Append string which represents all hints in a given state to buf, with
1024 * preceding title with them.
1027 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1032 appendStringInfo(buf, "%s:\n", title);
1033 for (i = 0; i < hstate->nall_hints; i++)
1035 if (hstate->all_hints[i]->state != state)
1038 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
1043 * Dump contents of given hstate to server log with log level LOG.
1046 HintStateDump(HintState *hstate)
1052 elog(LOG, "pg_hint_plan:\nno hint");
1056 initStringInfo(&buf);
1058 appendStringInfoString(&buf, "pg_hint_plan:\n");
1059 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
1060 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
1061 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
1062 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
1064 elog(LOG, "%s", buf.data);
1074 RelnameCmp(const void *a, const void *b)
1076 const char *relnamea = *((const char **) a);
1077 const char *relnameb = *((const char **) b);
1079 return strcmp(relnamea, relnameb);
1083 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1085 return RelnameCmp(&a->relname, &b->relname);
1089 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1093 if (a->nrels != b->nrels)
1094 return a->nrels - b->nrels;
1096 for (i = 0; i < a->nrels; i++)
1099 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1107 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1113 SetHintCmp(const SetHint *a, const SetHint *b)
1115 return strcmp(a->name, b->name);
1119 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1123 if (a->nrels != b->nrels)
1124 return a->nrels - b->nrels;
1126 for (i = 0; i < a->nrels; i++)
1129 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1137 HintCmp(const void *a, const void *b)
1139 const Hint *hinta = *((const Hint **) a);
1140 const Hint *hintb = *((const Hint **) b);
1142 if (hinta->type != hintb->type)
1143 return hinta->type - hintb->type;
1144 if (hinta->state == HINT_STATE_ERROR)
1146 if (hintb->state == HINT_STATE_ERROR)
1148 return hinta->cmp_func(hinta, hintb);
1152 * Returns byte offset of hint b from hint a. If hint a was specified before
1153 * b, positive value is returned.
1156 HintCmpWithPos(const void *a, const void *b)
1158 const Hint *hinta = *((const Hint **) a);
1159 const Hint *hintb = *((const Hint **) b);
1162 result = HintCmp(a, b);
1164 result = hinta->hint_str - hintb->hint_str;
1173 parse_keyword(const char *str, StringInfo buf)
1177 while (!isspace(*str) && *str != '(' && *str != '\0')
1178 appendStringInfoCharMacro(buf, *str++);
1184 skip_parenthesis(const char *str, char parenthesis)
1188 if (*str != parenthesis)
1190 if (parenthesis == '(')
1191 hint_ereport(str, ("Opening parenthesis is necessary."));
1192 else if (parenthesis == ')')
1193 hint_ereport(str, ("Closing parenthesis is necessary."));
1204 * Parse a token from str, and store malloc'd copy into word. A token can be
1205 * quoted with '"'. Return value is pointer to unparsed portion of original
1206 * string, or NULL if an error occurred.
1208 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1211 parse_quoted_value(const char *str, char **word, bool truncate)
1216 /* Skip leading spaces. */
1219 initStringInfo(&buf);
1232 /* Double quotation must be closed. */
1236 hint_ereport(str, ("Unterminated quoted string."));
1241 * Skip escaped double quotation.
1243 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1244 * block comments) to be an object name, so users must specify
1245 * alias for such object names.
1247 * Those special names can be allowed if we care escaped slashes
1248 * and asterisks, but we don't.
1257 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1261 appendStringInfoCharMacro(&buf, *str++);
1266 hint_ereport(str, ("Zero-length delimited string."));
1273 /* Truncate name if it's too long */
1275 truncate_identifier(buf.data, strlen(buf.data), true);
1282 static OuterInnerRels *
1283 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1285 OuterInnerRels *outer_inner;
1287 outer_inner = palloc(sizeof(OuterInnerRels));
1288 outer_inner->relation = name;
1289 outer_inner->outer_inner_pair = outer_inner_list;
1295 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1297 List *outer_inner_pair = NIL;
1299 if ((str = skip_parenthesis(str, '(')) == NULL)
1304 /* Store words in parentheses into outer_inner_list. */
1305 while(*str != ')' && *str != '\0')
1307 OuterInnerRels *outer_inner_rels;
1311 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1319 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1322 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1325 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1330 (str = skip_parenthesis(str, ')')) == NULL)
1332 list_free(outer_inner_pair);
1336 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1342 parse_parentheses_Leading(const char *str, List **name_list,
1343 OuterInnerRels **outer_inner)
1346 bool truncate = true;
1348 if ((str = skip_parenthesis(str, '(')) == NULL)
1354 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1359 /* Store words in parentheses into name_list. */
1360 while(*str != ')' && *str != '\0')
1362 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1364 list_free(*name_list);
1368 *name_list = lappend(*name_list, name);
1373 if ((str = skip_parenthesis(str, ')')) == NULL)
1379 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1382 bool truncate = true;
1384 if ((str = skip_parenthesis(str, '(')) == NULL)
1389 /* Store words in parentheses into name_list. */
1390 while(*str != ')' && *str != '\0')
1392 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1394 list_free(*name_list);
1398 *name_list = lappend(*name_list, name);
1401 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1402 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1403 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1404 keyword == HINT_KEYWORD_SET)
1410 if ((str = skip_parenthesis(str, ')')) == NULL)
1416 parse_hints(HintState *hstate, Query *parse, const char *str)
1421 initStringInfo(&buf);
1422 while (*str != '\0')
1424 const HintParser *parser;
1426 /* in error message, we output the comment including the keyword. */
1427 head = (char *) str;
1429 /* parse only the keyword of the hint. */
1430 resetStringInfo(&buf);
1431 str = parse_keyword(str, &buf);
1433 for (parser = parsers; parser->keyword != NULL; parser++)
1435 char *keyword = parser->keyword;
1438 if (strcasecmp(buf.data, keyword) != 0)
1441 hint = parser->create_func(head, keyword, parser->hint_keyword);
1443 /* parser of each hint does parse in a parenthesis. */
1444 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1446 hint->delete_func(hint);
1452 * Add hint information into all_hints array. If we don't have
1453 * enough space, double the array.
1455 if (hstate->nall_hints == 0)
1457 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1458 hstate->all_hints = (Hint **)
1459 palloc(sizeof(Hint *) * hstate->max_all_hints);
1461 else if (hstate->nall_hints == hstate->max_all_hints)
1463 hstate->max_all_hints *= 2;
1464 hstate->all_hints = (Hint **)
1465 repalloc(hstate->all_hints,
1466 sizeof(Hint *) * hstate->max_all_hints);
1469 hstate->all_hints[hstate->nall_hints] = hint;
1470 hstate->nall_hints++;
1477 if (parser->keyword == NULL)
1480 ("Unrecognized hint keyword \"%s\".", buf.data));
1491 * Get hints from table by client-supplied query string and application name.
1494 get_hints_from_table(const char *client_query, const char *client_application)
1496 const char *search_query =
1498 " FROM hint_plan.hints "
1499 " WHERE norm_query_string = $1 "
1500 " AND ( application_name = $2 "
1501 " OR application_name = '' ) "
1502 " ORDER BY application_name DESC";
1503 static SPIPlanPtr plan = NULL;
1505 Oid argtypes[2] = { TEXTOID, TEXTOID };
1507 bool nulls[2] = { false, false };
1520 p = SPI_prepare(search_query, 2, argtypes);
1521 plan = SPI_saveplan(p);
1525 qry = cstring_to_text(client_query);
1526 app = cstring_to_text(client_application);
1527 values[0] = PointerGetDatum(qry);
1528 values[1] = PointerGetDatum(app);
1530 SPI_execute_plan(plan, values, nulls, true, 1);
1532 if (SPI_processed > 0)
1536 hints = SPI_getvalue(SPI_tuptable->vals[0],
1537 SPI_tuptable->tupdesc, 1);
1539 * Here we use SPI_palloc to ensure that hints string is valid even
1540 * after SPI_finish call. We can't use simple palloc because it
1541 * allocates memory in SPI's context and that context is deleted in
1544 buf = SPI_palloc(strlen(hints) + 1);
1564 * Get client-supplied query string.
1567 get_query_string(void)
1573 PreparedStatement *entry;
1575 entry = FetchPreparedStatement(stmt_name, true);
1576 p = entry->plansource->query_string;
1578 else if (plpgsql_query_string)
1579 p = plpgsql_query_string;
1581 p = debug_query_string;
1587 * Get hints from the head block comment in client-supplied query string.
1590 get_hints_from_comment(const char *p)
1592 const char *hint_head;
1600 /* extract query head comment. */
1601 hint_head = strstr(p, HINT_START);
1602 if (hint_head == NULL)
1604 for (;p < hint_head; p++)
1607 * Allow these characters precedes hint comment:
1609 * - alphabets which are in ASCII range
1610 * - space, tabs and new-lines
1611 * - underscores, for identifier
1612 * - commas, for SELECT clause, EXPLAIN and PREPARE
1613 * - parentheses, for EXPLAIN and PREPARE
1615 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1616 * avoid behavior which depends on locale setting.
1618 if (!(*p >= '0' && *p <= '9') &&
1619 !(*p >= 'A' && *p <= 'Z') &&
1620 !(*p >= 'a' && *p <= 'z') &&
1624 *p != '(' && *p != ')')
1628 len = strlen(HINT_START);
1633 /* find hint end keyword. */
1634 if ((tail = strstr(p, HINT_END)) == NULL)
1636 hint_ereport(head, ("Unterminated block comment."));
1640 /* We don't support nested block comments. */
1641 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1643 hint_ereport(head, ("Nested block comments are not supported."));
1647 /* Make a copy of hint. */
1649 head = palloc(len + 1);
1650 memcpy(head, p, len);
1658 * Parse hints that got, create hint struct from parse tree and parse hints.
1661 create_hintstate(Query *parse, const char *hints)
1671 hstate = HintStateCreate();
1672 hstate->hint_str = (char *) hints;
1674 /* parse each hint. */
1675 parse_hints(hstate, parse, p);
1677 /* When nothing specified a hint, we free HintState and returns NULL. */
1678 if (hstate->nall_hints == 0)
1680 HintStateDelete(hstate);
1684 /* Sort hints in order of original position. */
1685 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1688 /* Count number of hints per hint-type. */
1689 for (i = 0; i < hstate->nall_hints; i++)
1691 Hint *cur_hint = hstate->all_hints[i];
1692 hstate->num_hints[cur_hint->type]++;
1696 * If an object (or a set of objects) has multiple hints of same hint-type,
1697 * only the last hint is valid and others are ignored in planning.
1698 * Hints except the last are marked as 'duplicated' to remember the order.
1700 for (i = 0; i < hstate->nall_hints - 1; i++)
1702 Hint *cur_hint = hstate->all_hints[i];
1703 Hint *next_hint = hstate->all_hints[i + 1];
1706 * Leading hint is marked as 'duplicated' in transform_join_hints.
1708 if (cur_hint->type == HINT_TYPE_LEADING &&
1709 next_hint->type == HINT_TYPE_LEADING)
1713 * Note that we need to pass addresses of hint pointers, because
1714 * HintCmp is designed to sort array of Hint* by qsort.
1716 if (HintCmp(&cur_hint, &next_hint) == 0)
1718 hint_ereport(cur_hint->hint_str,
1719 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1720 cur_hint->state = HINT_STATE_DUPLICATION;
1725 * Make sure that per-type array pointers point proper position in the
1726 * array which consists of all hints.
1728 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1729 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1730 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1731 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1732 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1733 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1734 hstate->num_hints[HINT_TYPE_LEADING]);
1735 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1736 hstate->num_hints[HINT_TYPE_SET]);
1742 * Parse inside of parentheses of scan-method hints.
1745 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1748 const char *keyword = hint->base.keyword;
1749 HintKeyword hint_keyword = hint->base.hint_keyword;
1750 List *name_list = NIL;
1753 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1756 /* Parse relation name and index name(s) if given hint accepts. */
1757 length = list_length(name_list);
1760 hint->relname = linitial(name_list);
1761 hint->indexnames = list_delete_first(name_list);
1763 /* check whether the hint accepts index name(s). */
1765 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1766 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1767 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1768 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1769 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1770 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1773 ("%s hint accepts only one relation.",
1774 hint->base.keyword));
1775 hint->base.state = HINT_STATE_ERROR;
1782 ("%s hint requires a relation.",
1783 hint->base.keyword));
1784 hint->base.state = HINT_STATE_ERROR;
1788 /* Set a bit for specified hint. */
1789 switch (hint_keyword)
1791 case HINT_KEYWORD_SEQSCAN:
1792 hint->enforce_mask = ENABLE_SEQSCAN;
1794 case HINT_KEYWORD_INDEXSCAN:
1795 hint->enforce_mask = ENABLE_INDEXSCAN;
1797 case HINT_KEYWORD_INDEXSCANREGEXP:
1798 hint->enforce_mask = ENABLE_INDEXSCAN;
1799 hint->regexp = true;
1801 case HINT_KEYWORD_BITMAPSCAN:
1802 hint->enforce_mask = ENABLE_BITMAPSCAN;
1804 case HINT_KEYWORD_BITMAPSCANREGEXP:
1805 hint->enforce_mask = ENABLE_BITMAPSCAN;
1806 hint->regexp = true;
1808 case HINT_KEYWORD_TIDSCAN:
1809 hint->enforce_mask = ENABLE_TIDSCAN;
1811 case HINT_KEYWORD_NOSEQSCAN:
1812 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1814 case HINT_KEYWORD_NOINDEXSCAN:
1815 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1817 case HINT_KEYWORD_NOBITMAPSCAN:
1818 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1820 case HINT_KEYWORD_NOTIDSCAN:
1821 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1823 case HINT_KEYWORD_INDEXONLYSCAN:
1824 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1826 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1827 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1828 hint->regexp = true;
1830 case HINT_KEYWORD_NOINDEXONLYSCAN:
1831 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1834 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1843 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1846 const char *keyword = hint->base.keyword;
1847 HintKeyword hint_keyword = hint->base.hint_keyword;
1848 List *name_list = NIL;
1850 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1853 hint->nrels = list_length(name_list);
1855 if (hint->nrels > 0)
1861 * Transform relation names from list to array to sort them with qsort
1864 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1865 foreach (l, name_list)
1867 hint->relnames[i] = lfirst(l);
1872 list_free(name_list);
1874 /* A join hint requires at least two relations */
1875 if (hint->nrels < 2)
1878 ("%s hint requires at least two relations.",
1879 hint->base.keyword));
1880 hint->base.state = HINT_STATE_ERROR;
1884 /* Sort hints in alphabetical order of relation names. */
1885 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1887 switch (hint_keyword)
1889 case HINT_KEYWORD_NESTLOOP:
1890 hint->enforce_mask = ENABLE_NESTLOOP;
1892 case HINT_KEYWORD_MERGEJOIN:
1893 hint->enforce_mask = ENABLE_MERGEJOIN;
1895 case HINT_KEYWORD_HASHJOIN:
1896 hint->enforce_mask = ENABLE_HASHJOIN;
1898 case HINT_KEYWORD_NONESTLOOP:
1899 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1901 case HINT_KEYWORD_NOMERGEJOIN:
1902 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1904 case HINT_KEYWORD_NOHASHJOIN:
1905 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1908 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1917 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1920 if (outer_inner->outer_inner_pair == NIL)
1922 if (outer_inner->relation)
1928 if (list_length(outer_inner->outer_inner_pair) == 2)
1930 foreach(l, outer_inner->outer_inner_pair)
1932 if (!OuterInnerPairCheck(lfirst(l)))
1943 OuterInnerList(OuterInnerRels *outer_inner)
1945 List *outer_inner_list = NIL;
1947 OuterInnerRels *outer_inner_rels;
1949 foreach(l, outer_inner->outer_inner_pair)
1951 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1953 if (outer_inner_rels->relation != NULL)
1954 outer_inner_list = lappend(outer_inner_list,
1955 outer_inner_rels->relation);
1957 outer_inner_list = list_concat(outer_inner_list,
1958 OuterInnerList(outer_inner_rels));
1960 return outer_inner_list;
1964 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1967 List *name_list = NIL;
1968 OuterInnerRels *outer_inner = NULL;
1970 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1974 if (outer_inner != NULL)
1975 name_list = OuterInnerList(outer_inner);
1977 hint->relations = name_list;
1978 hint->outer_inner = outer_inner;
1980 /* A Leading hint requires at least two relations */
1981 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1983 hint_ereport(hint->base.hint_str,
1984 ("%s hint requires at least two relations.",
1986 hint->base.state = HINT_STATE_ERROR;
1988 else if (hint->outer_inner != NULL &&
1989 !OuterInnerPairCheck(hint->outer_inner))
1991 hint_ereport(hint->base.hint_str,
1992 ("%s hint requires two sets of relations when parentheses nests.",
1994 hint->base.state = HINT_STATE_ERROR;
2001 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2003 List *name_list = NIL;
2005 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2009 hint->words = name_list;
2011 /* We need both name and value to set GUC parameter. */
2012 if (list_length(name_list) == 2)
2014 hint->name = linitial(name_list);
2015 hint->value = lsecond(name_list);
2019 hint_ereport(hint->base.hint_str,
2020 ("%s hint requires name and value of GUC parameter.",
2022 hint->base.state = HINT_STATE_ERROR;
2029 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2032 HintKeyword hint_keyword = hint->base.hint_keyword;
2033 List *name_list = NIL;
2037 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2040 /* Last element must be rows specification */
2041 hint->nrels = list_length(name_list) - 1;
2043 if (hint->nrels > 0)
2049 * Transform relation names from list to array to sort them with qsort
2052 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2053 foreach (l, name_list)
2055 if (hint->nrels <= i)
2057 hint->relnames[i] = lfirst(l);
2062 /* Retieve rows estimation */
2063 rows_str = list_nth(name_list, hint->nrels);
2064 hint->rows_str = rows_str; /* store as-is for error logging */
2065 if (rows_str[0] == '#')
2067 hint->value_type = RVT_ABSOLUTE;
2070 else if (rows_str[0] == '+')
2072 hint->value_type = RVT_ADD;
2075 else if (rows_str[0] == '-')
2077 hint->value_type = RVT_SUB;
2080 else if (rows_str[0] == '*')
2082 hint->value_type = RVT_MULTI;
2087 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2088 hint->base.state = HINT_STATE_ERROR;
2091 hint->rows = strtod(rows_str, &end_ptr);
2094 hint_ereport(rows_str,
2095 ("%s hint requires valid number as rows estimation.",
2096 hint->base.keyword));
2097 hint->base.state = HINT_STATE_ERROR;
2101 /* A join hint requires at least two relations */
2102 if (hint->nrels < 2)
2105 ("%s hint requires at least two relations.",
2106 hint->base.keyword));
2107 hint->base.state = HINT_STATE_ERROR;
2111 list_free(name_list);
2113 /* Sort relnames in alphabetical order. */
2114 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2120 * set GUC parameter functions
2124 set_config_option_wrapper(const char *name, const char *value,
2125 GucContext context, GucSource source,
2126 GucAction action, bool changeVal, int elevel)
2129 MemoryContext ccxt = CurrentMemoryContext;
2133 result = set_config_option(name, value, context, source,
2134 action, changeVal, 0);
2140 /* Save error info */
2141 MemoryContextSwitchTo(ccxt);
2142 errdata = CopyErrorData();
2145 ereport(elevel, (errcode(errdata->sqlerrcode),
2146 errmsg("%s", errdata->message),
2147 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2148 errdata->hint ? errhint("%s", errdata->hint) : 0));
2149 FreeErrorData(errdata);
2157 set_config_options(SetHint **options, int noptions, GucContext context)
2162 save_nestlevel = NewGUCNestLevel();
2164 for (i = 0; i < noptions; i++)
2166 SetHint *hint = options[i];
2169 if (!hint_state_enabled(hint))
2172 result = set_config_option_wrapper(hint->name, hint->value, context,
2173 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2174 pg_hint_plan_parse_messages);
2176 hint->base.state = HINT_STATE_USED;
2178 hint->base.state = HINT_STATE_ERROR;
2181 return save_nestlevel;
2184 #define SET_CONFIG_OPTION(name, type_bits) \
2185 set_config_option_wrapper((name), \
2186 (mask & (type_bits)) ? "true" : "false", \
2187 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2190 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2194 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2195 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2196 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2198 mask = enforce_mask;
2200 mask = enforce_mask & current_hint->init_scan_mask;
2202 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2203 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2204 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2205 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2206 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2210 set_join_config_options(unsigned char enforce_mask, GucContext context)
2214 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2215 enforce_mask == ENABLE_HASHJOIN)
2216 mask = enforce_mask;
2218 mask = enforce_mask & current_hint->init_join_mask;
2220 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2221 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2222 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2226 * pg_hint_plan hook functions
2230 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2231 ParamListInfo params, bool isTopLevel,
2232 DestReceiver *dest, char *completionTag)
2237 * Use standard planner if pg_hint_plan is disabled or current nesting
2238 * depth is nesting depth of SPI calls.
2240 if (!pg_hint_plan_enable_hint || nested_level > 0)
2242 if (prev_ProcessUtility)
2243 (*prev_ProcessUtility) (parsetree, queryString, params,
2244 isTopLevel, dest, completionTag);
2246 standard_ProcessUtility(parsetree, queryString, params,
2247 isTopLevel, dest, completionTag);
2253 if (IsA(node, ExplainStmt))
2256 * Draw out parse tree of actual query from Query struct of EXPLAIN
2262 stmt = (ExplainStmt *) node;
2264 Assert(IsA(stmt->query, Query));
2265 query = (Query *) stmt->query;
2267 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2268 node = query->utilityStmt;
2272 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2273 * specified to preceding PREPARE command to use it as source of hints.
2275 if (IsA(node, ExecuteStmt))
2279 stmt = (ExecuteStmt *) node;
2280 stmt_name = stmt->name;
2284 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2287 if (IsA(node, CreateTableAsStmt))
2289 CreateTableAsStmt *stmt;
2292 stmt = (CreateTableAsStmt *) node;
2293 Assert(IsA(stmt->query, Query));
2294 query = (Query *) stmt->query;
2296 if (query->commandType == CMD_UTILITY &&
2297 IsA(query->utilityStmt, ExecuteStmt))
2299 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2300 stmt_name = estmt->name;
2308 if (prev_ProcessUtility)
2309 (*prev_ProcessUtility) (parsetree, queryString, params,
2310 isTopLevel, dest, completionTag);
2312 standard_ProcessUtility(parsetree, queryString, params,
2313 isTopLevel, dest, completionTag);
2327 if (prev_ProcessUtility)
2328 (*prev_ProcessUtility) (parsetree, queryString, params,
2329 isTopLevel, dest, completionTag);
2331 standard_ProcessUtility(parsetree, queryString, params,
2332 isTopLevel, dest, completionTag);
2336 * Push a hint into hint stack which is implemented with List struct. Head of
2337 * list is top of stack.
2340 push_hint(HintState *hstate)
2342 /* Prepend new hint to the list means pushing to stack. */
2343 HintStateStack = lcons(hstate, HintStateStack);
2345 /* Pushed hint is the one which should be used hereafter. */
2346 current_hint = hstate;
2349 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2353 /* Hint stack must not be empty. */
2354 if(HintStateStack == NIL)
2355 elog(ERROR, "hint stack is empty");
2358 * Take a hint at the head from the list, and free it. Switch current_hint
2359 * to point new head (NULL if the list is empty).
2361 HintStateStack = list_delete_first(HintStateStack);
2362 HintStateDelete(current_hint);
2363 if(HintStateStack == NIL)
2364 current_hint = NULL;
2366 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2369 static PlannedStmt *
2370 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2372 const char *hints = NULL;
2375 pgssJumbleState jstate;
2378 PlannedStmt *result;
2382 * Use standard planner if pg_hint_plan is disabled or current nesting
2383 * depth is nesting depth of SPI calls. Other hook functions try to change
2384 * plan with current_hint if any, so set it to NULL.
2386 if (!pg_hint_plan_enable_hint || nested_level > 0)
2387 goto standard_planner_proc;
2389 /* Create hint struct from client-supplied query string. */
2390 query = get_query_string();
2393 * Create hintstate from hint specified for the query, if any.
2395 * First we lookup hint in pg_hint.hints table by normalized query string,
2396 * unless pg_hint_plan.enable_hint_table is OFF.
2397 * This parameter provides option to avoid overhead of table lookup during
2400 * If no hint was found, then we try to get hint from special query comment.
2402 if (pg_hint_plan_enable_hint_table)
2405 * Search hint information which is stored for the query and the
2406 * application. Query string is normalized before using in condition
2407 * in order to allow fuzzy matching.
2409 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2410 * careful when supporting PostgreSQL's version up.
2412 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2413 jstate.jumble_len = 0;
2414 jstate.clocations_buf_size = 32;
2415 jstate.clocations = (pgssLocationLen *)
2416 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2417 jstate.clocations_count = 0;
2418 JumbleQuery(&jstate, parse);
2420 * generate_normalized_query() copies exact given query_len bytes, so we
2421 * add 1 byte for null-termination here. As comments on
2422 * generate_normalized_query says, generate_normalized_query doesn't
2423 * take care of null-terminate, but additional 1 byte ensures that '\0'
2424 * byte in the source buffer to be copied into norm_query.
2426 query_len = strlen(query) + 1;
2427 norm_query = generate_normalized_query(&jstate,
2430 GetDatabaseEncoding());
2431 hints = get_hints_from_table(norm_query, application_name);
2433 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2434 norm_query, application_name, hints ? hints : "(none)");
2437 hints = get_hints_from_comment(query);
2438 hstate = create_hintstate(parse, hints);
2441 * Use standard planner if the statement has not valid hint. Other hook
2442 * functions try to change plan with current_hint if any, so set it to
2446 goto standard_planner_proc;
2449 * Push new hint struct to the hint stack to disable previous hint context.
2453 /* Set GUC parameters which are specified with Set hint. */
2454 save_nestlevel = set_config_options(current_hint->set_hints,
2455 current_hint->num_hints[HINT_TYPE_SET],
2456 current_hint->context);
2459 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2460 if (enable_indexscan)
2461 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2462 if (enable_bitmapscan)
2463 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2465 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2466 if (enable_indexonlyscan)
2467 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2468 if (enable_nestloop)
2469 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2470 if (enable_mergejoin)
2471 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2472 if (enable_hashjoin)
2473 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2476 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2477 * state when this planner started when error occurred in planner.
2482 result = (*prev_planner) (parse, cursorOptions, boundParams);
2484 result = standard_planner(parse, cursorOptions, boundParams);
2489 * Rollback changes of GUC parameters, and pop current hint context
2490 * from hint stack to rewind the state.
2492 AtEOXact_GUC(true, save_nestlevel);
2498 /* Print hint in debug mode. */
2499 if (pg_hint_plan_debug_print)
2500 HintStateDump(current_hint);
2503 * Rollback changes of GUC parameters, and pop current hint context from
2504 * hint stack to rewind the state.
2506 AtEOXact_GUC(true, save_nestlevel);
2511 standard_planner_proc:
2512 current_hint = NULL;
2514 return (*prev_planner) (parse, cursorOptions, boundParams);
2516 return standard_planner(parse, cursorOptions, boundParams);
2520 * Return scan method hint which matches given aliasname.
2522 static ScanMethodHint *
2523 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2529 * We can't apply scan method hint if the relation is:
2530 * - not a base relation
2531 * - not an ordinary relation (such as join and subquery)
2533 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2536 rte = root->simple_rte_array[rel->relid];
2538 /* We can't force scan method of foreign tables */
2539 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2542 /* Find scan method hint, which matches given names, from the list. */
2543 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2545 ScanMethodHint *hint = current_hint->scan_hints[i];
2547 /* We ignore disabled hints. */
2548 if (!hint_state_enabled(hint))
2551 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2561 * Returns TRUE on match, FALSE on no match.
2563 * s1 --- the data to match against
2564 * s2 --- the pattern
2566 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2569 regexpeq(const char *s1, const char *s2)
2575 strcpy(name.data, s1);
2576 regexp = cstring_to_text(s2);
2578 result = DirectFunctionCall2Coll(nameregexeq,
2579 DEFAULT_COLLATION_OID,
2580 NameGetDatum(&name),
2581 PointerGetDatum(regexp));
2582 return DatumGetBool(result);
2586 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2594 * We delete all the IndexOptInfo list and prevent you from being usable by
2597 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2598 hint->enforce_mask == ENABLE_TIDSCAN)
2600 list_free_deep(rel->indexlist);
2601 rel->indexlist = NIL;
2602 hint->base.state = HINT_STATE_USED;
2608 * When a list of indexes is not specified, we just use all indexes.
2610 if (hint->indexnames == NIL)
2614 * Leaving only an specified index, we delete it from a IndexOptInfo list
2618 if (pg_hint_plan_debug_print)
2619 initStringInfo(&buf);
2621 for (cell = list_head(rel->indexlist); cell; cell = next)
2623 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2624 char *indexname = get_rel_name(info->indexoid);
2626 bool use_index = false;
2630 foreach(l, hint->indexnames)
2632 char *hintname = (char *) lfirst(l);
2636 result = regexpeq(indexname, hintname);
2638 result = RelnameCmp(&indexname, &hintname) == 0;
2643 if (pg_hint_plan_debug_print)
2645 appendStringInfoCharMacro(&buf, ' ');
2646 quote_value(&buf, indexname);
2654 * to make the index a candidate when definition of this index is
2655 * matched with the index's definition of current_hint.
2657 if (OidIsValid(relationObjectId) && !use_index)
2659 foreach(l, current_hint->parent_index_infos)
2663 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2665 /* check to match the parameter of unique */
2666 if (p_info->indisunique != info->unique)
2669 /* check to match the parameter of index's method */
2670 if (p_info->method != info->relam)
2673 /* to check to match the indexkey's configuration */
2674 if ((list_length(p_info->column_names)) !=
2678 /* check to match the indexkey's configuration */
2679 for (i = 0; i < info->ncolumns; i++)
2681 char *c_attname = NULL;
2682 char *p_attname = NULL;
2685 list_nth(p_info->column_names, i);
2687 /* both are expressions */
2688 if (info->indexkeys[i] == 0 && !p_attname)
2691 /* one's column is expression, the other is not */
2692 if (info->indexkeys[i] == 0 || !p_attname)
2695 c_attname = get_attname(relationObjectId,
2696 info->indexkeys[i]);
2698 if (strcmp(p_attname, c_attname) != 0)
2701 if (p_info->indcollation[i] != info->indexcollations[i])
2704 if (p_info->opclass[i] != info->opcintype[i])
2707 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2708 info->reverse_sort[i])
2711 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2712 info->nulls_first[i])
2717 if (i != info->ncolumns)
2720 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2721 (p_info->indpred_str && (info->indpred != NIL)))
2724 * Fetch the pg_index tuple by the Oid of the index
2726 ht_idx = SearchSysCache1(INDEXRELID,
2727 ObjectIdGetDatum(info->indexoid));
2729 /* check to match the expression's parameter of index */
2730 if (p_info->expression_str &&
2731 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2738 * to change the expression's parameter of child's
2741 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2742 Anum_pg_index_indexprs,
2745 result = DirectFunctionCall2(pg_get_expr,
2750 if (strcmp(p_info->expression_str,
2751 text_to_cstring(DatumGetTextP(result))) != 0)
2754 ReleaseSysCache(ht_idx);
2760 /* Check to match the predicate's parameter of index */
2761 if (p_info->indpred_str &&
2762 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2769 * to change the predicate's parameter of child's
2772 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2773 Anum_pg_index_indpred,
2776 result = DirectFunctionCall2(pg_get_expr,
2781 if (strcmp(p_info->indpred_str,
2782 text_to_cstring(DatumGetTextP(result))) != 0)
2785 ReleaseSysCache(ht_idx);
2792 ReleaseSysCache(ht_idx);
2794 else if (p_info->expression_str || (info->indexprs != NIL))
2796 else if (p_info->indpred_str || (info->indpred != NIL))
2801 /* to log the candidate of index */
2802 if (pg_hint_plan_debug_print)
2804 appendStringInfoCharMacro(&buf, ' ');
2805 quote_value(&buf, indexname);
2813 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2820 if (pg_hint_plan_debug_print)
2823 StringInfoData rel_buf;
2825 if (OidIsValid(relationObjectId))
2826 relname = get_rel_name(relationObjectId);
2828 relname = hint->relname;
2830 initStringInfo(&rel_buf);
2831 quote_value(&rel_buf, relname);
2834 (errmsg("available indexes for %s(%s):%s",
2839 pfree(rel_buf.data);
2844 * Return information of index definition.
2846 static ParentIndexInfo *
2847 get_parent_index_info(Oid indexoid, Oid relid)
2849 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2850 Relation indexRelation;
2851 Form_pg_index index;
2855 indexRelation = index_open(indexoid, RowExclusiveLock);
2857 index = indexRelation->rd_index;
2859 p_info->indisunique = index->indisunique;
2860 p_info->method = indexRelation->rd_rel->relam;
2862 p_info->column_names = NIL;
2863 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2864 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2865 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2867 for (i = 0; i < index->indnatts; i++)
2869 attname = get_attname(relid, index->indkey.values[i]);
2870 p_info->column_names = lappend(p_info->column_names, attname);
2872 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2873 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2874 p_info->indoption[i] = indexRelation->rd_indoption[i];
2878 * to check to match the expression's parameter of index with child indexes
2880 p_info->expression_str = NULL;
2881 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2887 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2888 Anum_pg_index_indexprs, &isnull);
2890 result = DirectFunctionCall2(pg_get_expr,
2892 ObjectIdGetDatum(relid));
2894 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2898 * to check to match the predicate's parameter of index with child indexes
2900 p_info->indpred_str = NULL;
2901 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2907 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2908 Anum_pg_index_indpred, &isnull);
2910 result = DirectFunctionCall2(pg_get_expr,
2912 ObjectIdGetDatum(relid));
2914 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2917 index_close(indexRelation, NoLock);
2923 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2924 bool inhparent, RelOptInfo *rel)
2926 ScanMethodHint *hint;
2928 if (prev_get_relation_info)
2929 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2932 * Do nothing if we don't have valid hint in this context or current
2933 * nesting depth is nesting depth of SPI calls.
2935 if (!current_hint || nested_level > 0)
2940 /* store does relids of parent table. */
2941 current_hint->parent_relid = rel->relid;
2943 else if (current_hint->parent_relid != 0)
2946 * We use the same GUC parameter if this table is the child table of a
2947 * table called pg_hint_plan_get_relation_info just before that.
2951 /* append_rel_list contains all append rels; ignore others */
2952 foreach(l, root->append_rel_list)
2954 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2956 /* This rel is child table. */
2957 if (appinfo->parent_relid == current_hint->parent_relid &&
2958 appinfo->child_relid == rel->relid)
2960 if (current_hint->parent_hint)
2961 delete_indexes(current_hint->parent_hint, rel,
2968 /* This rel is not inherit table. */
2969 current_hint->parent_relid = 0;
2970 current_hint->parent_hint = NULL;
2974 * If scan method hint was given, reset GUC parameters which control
2975 * planner behavior about choosing scan methods.
2977 if ((hint = find_scan_hint(root, rel)) == NULL)
2979 set_scan_config_options(current_hint->init_scan_mask,
2980 current_hint->context);
2983 set_scan_config_options(hint->enforce_mask, current_hint->context);
2984 hint->base.state = HINT_STATE_USED;
2992 current_hint->parent_hint = hint;
2994 relation = heap_open(relationObjectId, NoLock);
2995 indexoidlist = RelationGetIndexList(relation);
2997 foreach(l, indexoidlist)
2999 Oid indexoid = lfirst_oid(l);
3000 char *indexname = get_rel_name(indexoid);
3001 bool use_index = false;
3003 ParentIndexInfo *parent_index_info;
3005 foreach(lc, hint->indexnames)
3007 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3016 parent_index_info = get_parent_index_info(indexoid,
3018 current_hint->parent_index_infos =
3019 lappend(current_hint->parent_index_infos, parent_index_info);
3021 heap_close(relation, NoLock);
3024 delete_indexes(hint, rel, InvalidOid);
3028 * Return index of relation which matches given aliasname, or 0 if not found.
3029 * If same aliasname was used multiple times in a query, return -1.
3032 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3038 for (i = 1; i < root->simple_rel_array_size; i++)
3042 if (root->simple_rel_array[i] == NULL)
3045 Assert(i == root->simple_rel_array[i]->relid);
3047 if (RelnameCmp(&aliasname,
3048 &root->simple_rte_array[i]->eref->aliasname) != 0)
3051 foreach(l, initial_rels)
3053 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3055 if (rel->reloptkind == RELOPT_BASEREL)
3057 if (rel->relid != i)
3062 Assert(rel->reloptkind == RELOPT_JOINREL);
3064 if (!bms_is_member(i, rel->relids))
3071 ("Relation name \"%s\" is ambiguous.",
3086 * Return join hint which matches given joinrelids.
3088 static JoinMethodHint *
3089 find_join_hint(Relids joinrelids)
3094 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3096 foreach(l, join_hint)
3098 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3100 if (bms_equal(joinrelids, hint->joinrelids))
3108 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3109 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3111 OuterInnerRels *outer_rels;
3112 OuterInnerRels *inner_rels;
3113 Relids outer_relids;
3114 Relids inner_relids;
3116 JoinMethodHint *hint;
3118 if (outer_inner->relation != NULL)
3120 return bms_make_singleton(
3121 find_relid_aliasname(root, outer_inner->relation,
3123 leading_hint->base.hint_str));
3126 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3127 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3129 outer_relids = OuterInnerJoinCreate(outer_rels,
3135 inner_relids = OuterInnerJoinCreate(inner_rels,
3142 join_relids = bms_add_members(outer_relids, inner_relids);
3144 if (bms_num_members(join_relids) > nbaserel)
3148 * If we don't have join method hint, create new one for the
3149 * join combination with all join methods are enabled.
3151 hint = find_join_hint(join_relids);
3155 * Here relnames is not set, since Relids bitmap is sufficient to
3156 * control paths of this query afterward.
3158 hint = (JoinMethodHint *) JoinMethodHintCreate(
3159 leading_hint->base.hint_str,
3161 HINT_KEYWORD_LEADING);
3162 hint->base.state = HINT_STATE_USED;
3163 hint->nrels = bms_num_members(join_relids);
3164 hint->enforce_mask = ENABLE_ALL_JOIN;
3165 hint->joinrelids = bms_copy(join_relids);
3166 hint->inner_nrels = bms_num_members(inner_relids);
3167 hint->inner_joinrelids = bms_copy(inner_relids);
3169 hstate->join_hint_level[hint->nrels] =
3170 lappend(hstate->join_hint_level[hint->nrels], hint);
3174 hint->inner_nrels = bms_num_members(inner_relids);
3175 hint->inner_joinrelids = bms_copy(inner_relids);
3182 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3183 int nrels, char **relnames)
3186 Relids relids = NULL;
3190 for (j = 0; j < nrels; j++)
3192 relname = relnames[j];
3194 relid = find_relid_aliasname(root, relname, initial_rels,
3198 base->state = HINT_STATE_ERROR;
3201 * the aliasname is not found(relid == 0) or same aliasname was used
3202 * multiple times in a query(relid == -1)
3209 if (bms_is_member(relid, relids))
3211 hint_ereport(base->hint_str,
3212 ("Relation name \"%s\" is duplicated.", relname));
3213 base->state = HINT_STATE_ERROR;
3217 relids = bms_add_member(relids, relid);
3222 * Transform join method hint into handy form.
3224 * - create bitmap of relids from alias names, to make it easier to check
3225 * whether a join path matches a join method hint.
3226 * - add join method hints which are necessary to enforce join order
3227 * specified by Leading hint
3230 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3231 List *initial_rels, JoinMethodHint **join_method_hints)
3239 LeadingHint *lhint = NULL;
3242 * Create bitmap of relids from alias names for each join method hint.
3243 * Bitmaps are more handy than strings in join searching.
3245 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3247 JoinMethodHint *hint = hstate->join_hints[i];
3249 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3252 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3253 initial_rels, hint->nrels, hint->relnames);
3255 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3258 hstate->join_hint_level[hint->nrels] =
3259 lappend(hstate->join_hint_level[hint->nrels], hint);
3263 * Create bitmap of relids from alias names for each rows hint.
3264 * Bitmaps are more handy than strings in join searching.
3266 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3268 RowsHint *hint = hstate->rows_hints[i];
3270 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3273 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3274 initial_rels, hint->nrels, hint->relnames);
3277 /* Do nothing if no Leading hint was supplied. */
3278 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3282 * Decide to use Leading hint。
3284 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3286 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3289 if (leading_hint->base.state == HINT_STATE_ERROR)
3295 foreach(l, leading_hint->relations)
3297 relname = (char *)lfirst(l);;
3299 relid = find_relid_aliasname(root, relname, initial_rels,
3300 leading_hint->base.hint_str);
3302 leading_hint->base.state = HINT_STATE_ERROR;
3307 if (bms_is_member(relid, relids))
3309 hint_ereport(leading_hint->base.hint_str,
3310 ("Relation name \"%s\" is duplicated.", relname));
3311 leading_hint->base.state = HINT_STATE_ERROR;
3315 relids = bms_add_member(relids, relid);
3318 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3323 hint_ereport(lhint->base.hint_str,
3324 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3325 lhint->base.state = HINT_STATE_DUPLICATION;
3327 leading_hint->base.state = HINT_STATE_USED;
3328 lhint = leading_hint;
3331 /* check to exist Leading hint marked with 'used'. */
3336 * We need join method hints which fit specified join order in every join
3337 * level. For example, Leading(A B C) virtually requires following join
3338 * method hints, if no join method hint supplied:
3340 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3341 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3343 * If we already have join method hint which fits specified join order in
3344 * that join level, we leave it as-is and don't add new hints.
3348 if (lhint->outer_inner == NULL)
3350 foreach(l, lhint->relations)
3352 JoinMethodHint *hint;
3354 relname = (char *)lfirst(l);
3357 * Find relid of the relation which has given name. If we have the
3358 * name given in Leading hint multiple times in the join, nothing to
3361 relid = find_relid_aliasname(root, relname, initial_rels,
3364 /* Create bitmap of relids for current join level. */
3365 joinrelids = bms_add_member(joinrelids, relid);
3368 /* We never have join method hint for single relation. */
3373 * If we don't have join method hint, create new one for the
3374 * join combination with all join methods are enabled.
3376 hint = find_join_hint(joinrelids);
3380 * Here relnames is not set, since Relids bitmap is sufficient
3381 * to control paths of this query afterward.
3383 hint = (JoinMethodHint *) JoinMethodHintCreate(
3384 lhint->base.hint_str,
3386 HINT_KEYWORD_LEADING);
3387 hint->base.state = HINT_STATE_USED;
3388 hint->nrels = njoinrels;
3389 hint->enforce_mask = ENABLE_ALL_JOIN;
3390 hint->joinrelids = bms_copy(joinrelids);
3393 join_method_hints[njoinrels] = hint;
3395 if (njoinrels >= nbaserel)
3398 bms_free(joinrelids);
3404 * Delete all join hints which have different combination from Leading
3407 for (i = 2; i <= njoinrels; i++)
3409 list_free(hstate->join_hint_level[i]);
3411 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3416 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3423 njoinrels = bms_num_members(joinrelids);
3424 Assert(njoinrels >= 2);
3427 * Delete all join hints which have different combination from Leading
3430 for (i = 2;i <= njoinrels; i++)
3432 if (hstate->join_hint_level[i] != NIL)
3434 ListCell *prev = NULL;
3435 ListCell *next = NULL;
3436 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3438 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3442 if (hint->inner_nrels == 0 &&
3443 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3444 bms_equal(bms_union(hint->joinrelids, joinrelids),
3447 hstate->join_hint_level[i] =
3448 list_delete_cell(hstate->join_hint_level[i], l,
3457 bms_free(joinrelids);
3460 if (hint_state_enabled(lhint))
3462 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3469 * set_plain_rel_pathlist
3470 * Build access paths for a plain relation (no subquery, no inheritance)
3472 * This function was copied and edited from set_plain_rel_pathlist() in
3473 * src/backend/optimizer/path/allpaths.c
3476 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3478 /* Consider sequential scan */
3479 add_path(rel, create_seqscan_path(root, rel, NULL));
3481 /* Consider index scans */
3482 create_index_paths(root, rel);
3484 /* Consider TID scans */
3485 create_tidscan_paths(root, rel);
3487 /* Now find the cheapest of the paths for this rel */
3492 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3497 foreach(l, initial_rels)
3499 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3501 ScanMethodHint *hint;
3503 /* Skip relations which we can't choose scan method. */
3504 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3507 rte = root->simple_rte_array[rel->relid];
3509 /* We can't force scan method of foreign tables */
3510 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3514 * Create scan paths with GUC parameters which are at the beginning of
3515 * planner if scan method hint is not specified, otherwise use
3516 * specified hints and mark the hint as used.
3518 if ((hint = find_scan_hint(root, rel)) == NULL)
3519 set_scan_config_options(hstate->init_scan_mask,
3523 set_scan_config_options(hint->enforce_mask, hstate->context);
3524 hint->base.state = HINT_STATE_USED;
3527 list_free_deep(rel->pathlist);
3528 rel->pathlist = NIL;
3531 /* It's an "append relation", process accordingly */
3532 set_append_rel_pathlist(root, rel, rel->relid, rte);
3536 set_plain_rel_pathlist(root, rel, rte);
3541 * Restore the GUC variables we set above.
3543 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3547 * wrapper of make_join_rel()
3549 * call make_join_rel() after changing enable_* parameters according to given
3553 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3556 JoinMethodHint *hint;
3560 joinrelids = bms_union(rel1->relids, rel2->relids);
3561 hint = find_join_hint(joinrelids);
3562 bms_free(joinrelids);
3565 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3567 if (hint->inner_nrels == 0)
3569 save_nestlevel = NewGUCNestLevel();
3571 set_join_config_options(hint->enforce_mask, current_hint->context);
3573 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3574 hint->base.state = HINT_STATE_USED;
3577 * Restore the GUC variables we set above.
3579 AtEOXact_GUC(true, save_nestlevel);
3582 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3591 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3592 RelOptInfo *joinrel,
3593 RelOptInfo *outerrel,
3594 RelOptInfo *innerrel,
3596 SpecialJoinInfo *sjinfo,
3599 ScanMethodHint *scan_hint = NULL;
3601 JoinMethodHint *join_hint;
3604 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3606 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3607 scan_hint->base.state = HINT_STATE_USED;
3610 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3612 join_hint = find_join_hint(joinrelids);
3613 bms_free(joinrelids);
3615 if (join_hint && join_hint->inner_nrels != 0)
3617 save_nestlevel = NewGUCNestLevel();
3619 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3622 set_join_config_options(join_hint->enforce_mask,
3623 current_hint->context);
3625 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3626 sjinfo, restrictlist);
3627 join_hint->base.state = HINT_STATE_USED;
3631 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3632 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3633 sjinfo, restrictlist);
3637 * Restore the GUC variables we set above.
3639 AtEOXact_GUC(true, save_nestlevel);
3642 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3643 sjinfo, restrictlist);
3645 if (scan_hint != NULL)
3646 set_scan_config_options(current_hint->init_scan_mask,
3647 current_hint->context);
3651 get_num_baserels(List *initial_rels)
3656 foreach(l, initial_rels)
3658 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3660 if (rel->reloptkind == RELOPT_BASEREL)
3662 else if (rel->reloptkind ==RELOPT_JOINREL)
3663 nbaserel+= bms_num_members(rel->relids);
3666 /* other values not expected here */
3667 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3675 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3678 JoinMethodHint **join_method_hints;
3682 bool leading_hint_enable;
3685 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3686 * valid hint is supplied or current nesting depth is nesting depth of SPI
3689 if (!current_hint || nested_level > 0)
3691 if (prev_join_search)
3692 return (*prev_join_search) (root, levels_needed, initial_rels);
3693 else if (enable_geqo && levels_needed >= geqo_threshold)
3694 return geqo(root, levels_needed, initial_rels);
3696 return standard_join_search(root, levels_needed, initial_rels);
3699 /* We apply scan method hint rebuild scan path. */
3700 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3703 * In the case using GEQO, only scan method hints and Set hints have
3704 * effect. Join method and join order is not controllable by hints.
3706 if (enable_geqo && levels_needed >= geqo_threshold)
3707 return geqo(root, levels_needed, initial_rels);
3709 nbaserel = get_num_baserels(initial_rels);
3710 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3711 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3713 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3714 initial_rels, join_method_hints);
3716 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3718 for (i = 2; i <= nbaserel; i++)
3720 list_free(current_hint->join_hint_level[i]);
3722 /* free Leading hint only */
3723 if (join_method_hints[i] != NULL &&
3724 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3725 JoinMethodHintDelete(join_method_hints[i]);
3727 pfree(current_hint->join_hint_level);
3728 pfree(join_method_hints);
3730 if (leading_hint_enable)
3731 set_join_config_options(current_hint->init_join_mask,
3732 current_hint->context);
3739 * Build access paths for a base relation
3741 * This function was copied and edited from set_rel_pathlist() in
3742 * src/backend/optimizer/path/allpaths.c
3745 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3746 Index rti, RangeTblEntry *rte)
3748 if (IS_DUMMY_REL(rel))
3750 /* We already proved the relation empty, so nothing more to do */
3754 /* It's an "append relation", process accordingly */
3755 set_append_rel_pathlist(root, rel, rti, rte);
3759 if (rel->rtekind == RTE_RELATION)
3761 if (rte->relkind == RELKIND_RELATION)
3763 /* Plain relation */
3764 set_plain_rel_pathlist(root, rel, rte);
3767 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3770 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3775 * stmt_beg callback is called when each query in PL/pgSQL function is about
3776 * to be executed. At that timing, we save query string in the global variable
3777 * plpgsql_query_string to use it in planner hook. It's safe to use one global
3778 * variable for the purpose, because its content is only necessary until
3779 * planner hook is called for the query, so recursive PL/pgSQL function calls
3780 * don't harm this mechanism.
3783 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3785 PLpgSQL_expr *expr = NULL;
3787 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
3789 case PLPGSQL_STMT_FORS:
3790 expr = ((PLpgSQL_stmt_fors *) stmt)->query;
3792 case PLPGSQL_STMT_FORC:
3793 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_forc *)stmt)->curvar]))->cursor_explicit_expr;
3795 case PLPGSQL_STMT_RETURN_QUERY:
3796 if (((PLpgSQL_stmt_return_query *) stmt)->query != NULL)
3797 expr = ((PLpgSQL_stmt_return_query *) stmt)->query;
3799 expr = ((PLpgSQL_stmt_return_query *) stmt)->dynquery;
3801 case PLPGSQL_STMT_EXECSQL:
3802 expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3804 case PLPGSQL_STMT_DYNEXECUTE:
3805 expr = ((PLpgSQL_stmt_dynexecute *) stmt)->query;
3807 case PLPGSQL_STMT_DYNFORS:
3808 expr = ((PLpgSQL_stmt_dynfors *) stmt)->query;
3810 case PLPGSQL_STMT_OPEN:
3811 if (((PLpgSQL_stmt_open *) stmt)->query != NULL)
3812 expr = ((PLpgSQL_stmt_open *) stmt)->query;
3813 else if (((PLpgSQL_stmt_open *) stmt)->dynquery != NULL)
3814 expr = ((PLpgSQL_stmt_open *) stmt)->dynquery;
3816 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_open *)stmt)->curvar]))->cursor_explicit_expr;
3823 plpgsql_query_string = expr->query;
3827 * stmt_end callback is called then each query in PL/pgSQL function has
3828 * finished. At that timing, we clear plpgsql_query_string to tell planner
3829 * hook that next call is not for a query written in PL/pgSQL block.
3832 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3834 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3835 plpgsql_query_string = NULL;
3838 #define standard_join_search pg_hint_plan_standard_join_search
3839 #define join_search_one_level pg_hint_plan_join_search_one_level
3840 #define make_join_rel make_join_rel_wrapper
3843 #undef make_join_rel
3844 #define make_join_rel pg_hint_plan_make_join_rel
3845 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3846 #include "make_join_rel.c"
3848 #include "pg_stat_statements.c"