1 /*-------------------------------------------------------------------------
4 * do instructions or hints to the planner using C-style block comments
7 * Copyright (c) 2012-2013, 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) */
273 RVT_DIV, /* Rows(... /100) */
275 typedef struct RowsHint
282 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 Oid parent_rel_oid; /* inherit parent table relid */
307 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
308 List *parent_index_infos; /* information of inherit parent table's
311 /* for join method hints */
312 JoinMethodHint **join_hints; /* parsed join hints */
313 int init_join_mask; /* initial value join parameter */
314 List **join_hint_level;
316 /* for Leading hint */
317 LeadingHint **leading_hint; /* parsed Leading hints */
320 SetHint **set_hints; /* parsed Set hints */
321 GucContext context; /* which GUC parameters can we set? */
324 RowsHint **rows_hints; /* parsed Rows hints */
328 * Describes a hint parser module which is bound with particular hint keyword.
330 typedef struct HintParser
333 HintCreateFunction create_func;
334 HintKeyword hint_keyword;
337 /* Module callbacks */
341 static void push_hint(HintState *hstate);
342 static void pop_hint(void);
344 static void pg_hint_plan_ProcessUtility(Node *parsetree,
345 const char *queryString,
346 ParamListInfo params, bool isTopLevel,
348 char *completionTag);
349 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
350 ParamListInfo boundParams);
351 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
352 Oid relationObjectId,
353 bool inhparent, RelOptInfo *rel);
354 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
358 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
359 HintKeyword hint_keyword);
360 static void ScanMethodHintDelete(ScanMethodHint *hint);
361 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
362 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
363 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
364 Query *parse, const char *str);
365 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
366 HintKeyword hint_keyword);
367 static void JoinMethodHintDelete(JoinMethodHint *hint);
368 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
369 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
370 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
371 Query *parse, const char *str);
372 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
373 HintKeyword hint_keyword);
374 static void LeadingHintDelete(LeadingHint *hint);
375 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
376 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
377 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
378 Query *parse, const char *str);
379 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
380 HintKeyword hint_keyword);
381 static void SetHintDelete(SetHint *hint);
382 static void SetHintDesc(SetHint *hint, StringInfo buf);
383 static int SetHintCmp(const SetHint *a, const SetHint *b);
384 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
386 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
387 HintKeyword hint_keyword);
388 static void RowsHintDelete(RowsHint *hint);
389 static void RowsHintDesc(RowsHint *hint, StringInfo buf);
390 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
391 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
392 Query *parse, const char *str);
393 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
394 HintKeyword hint_keyword);
396 static void quote_value(StringInfo buf, const char *value);
398 static const char *parse_quoted_value(const char *str, char **word,
401 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
404 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
405 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
406 ListCell *other_rels);
407 static void make_rels_by_clauseless_joins(PlannerInfo *root,
409 ListCell *other_rels);
410 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
411 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
412 Index rti, RangeTblEntry *rte);
413 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
414 List *live_childrels,
415 List *all_child_pathkeys);
416 static List *accumulate_append_subpath(List *subpaths, Path *path);
417 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
420 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
422 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
426 static bool pg_hint_plan_enable_hint = true;
427 static bool pg_hint_plan_debug_print = false;
428 static int pg_hint_plan_parse_messages = INFO;
429 /* Default is off, to keep backward compatibility. */
430 static bool pg_hint_plan_enable_hint_table = false;
432 static const struct config_enum_entry parse_messages_level_options[] = {
433 {"debug", DEBUG2, true},
434 {"debug5", DEBUG5, false},
435 {"debug4", DEBUG4, false},
436 {"debug3", DEBUG3, false},
437 {"debug2", DEBUG2, false},
438 {"debug1", DEBUG1, false},
440 {"info", INFO, false},
441 {"notice", NOTICE, false},
442 {"warning", WARNING, false},
443 {"error", ERROR, false},
445 * {"fatal", FATAL, true},
446 * {"panic", PANIC, true},
451 /* Saved hook values in case of unload */
452 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
453 static planner_hook_type prev_planner = NULL;
454 static get_relation_info_hook_type prev_get_relation_info = NULL;
455 static join_search_hook_type prev_join_search = NULL;
457 /* Hold reference to currently active hint */
458 static HintState *current_hint = NULL;
461 * List of hint contexts. We treat the head of the list as the Top of the
462 * context stack, so current_hint always points the first element of this list.
464 static List *HintStateStack = NIL;
467 * Holds statement name during executing EXECUTE command. NULL for other
470 static char *stmt_name = NULL;
472 static const HintParser parsers[] = {
473 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
474 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
475 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
476 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
477 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
478 HINT_KEYWORD_BITMAPSCANREGEXP},
479 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
480 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
481 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
482 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
483 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
484 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
485 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
486 HINT_KEYWORD_INDEXONLYSCANREGEXP},
487 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
488 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
489 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
490 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
491 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
492 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
493 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
494 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
495 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
496 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
497 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
501 * PL/pgSQL plugin for retrieving string representation of each query during
502 * function execution.
504 const char *plpgsql_query_string = NULL;
505 PLpgSQL_plugin plugin_funcs = {
509 pg_hint_plan_plpgsql_stmt_beg,
510 pg_hint_plan_plpgsql_stmt_end,
515 /* Current nesting depth of SPI calls, used to prevent recursive calls */
516 static int nested_level = 0;
519 * Module load callbacks
524 PLpgSQL_plugin **var_ptr;
526 /* Define custom GUC variables. */
527 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
528 "Force planner to use plans specified in the hint comment preceding to the query.",
530 &pg_hint_plan_enable_hint,
538 DefineCustomBoolVariable("pg_hint_plan.debug_print",
539 "Logs results of hint parsing.",
541 &pg_hint_plan_debug_print,
549 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
550 "Message level of parse errors.",
552 &pg_hint_plan_parse_messages,
554 parse_messages_level_options,
561 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
562 "Force planner to not get hint by using table lookups.",
564 &pg_hint_plan_enable_hint_table,
573 prev_ProcessUtility = ProcessUtility_hook;
574 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
575 prev_planner = planner_hook;
576 planner_hook = pg_hint_plan_planner;
577 prev_get_relation_info = get_relation_info_hook;
578 get_relation_info_hook = pg_hint_plan_get_relation_info;
579 prev_join_search = join_search_hook;
580 join_search_hook = pg_hint_plan_join_search;
582 /* setup PL/pgSQL plugin hook */
583 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
584 *var_ptr = &plugin_funcs;
588 * Module unload callback
594 PLpgSQL_plugin **var_ptr;
596 /* Uninstall hooks. */
597 ProcessUtility_hook = prev_ProcessUtility;
598 planner_hook = prev_planner;
599 get_relation_info_hook = prev_get_relation_info;
600 join_search_hook = prev_join_search;
602 /* uninstall PL/pgSQL plugin hook */
603 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
608 * create and delete functions the hint object
612 ScanMethodHintCreate(const char *hint_str, const char *keyword,
613 HintKeyword hint_keyword)
615 ScanMethodHint *hint;
617 hint = palloc(sizeof(ScanMethodHint));
618 hint->base.hint_str = hint_str;
619 hint->base.keyword = keyword;
620 hint->base.hint_keyword = hint_keyword;
621 hint->base.type = HINT_TYPE_SCAN_METHOD;
622 hint->base.state = HINT_STATE_NOTUSED;
623 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
624 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
625 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
626 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
627 hint->relname = NULL;
628 hint->indexnames = NIL;
629 hint->regexp = false;
630 hint->enforce_mask = 0;
632 return (Hint *) hint;
636 ScanMethodHintDelete(ScanMethodHint *hint)
642 pfree(hint->relname);
643 list_free_deep(hint->indexnames);
648 JoinMethodHintCreate(const char *hint_str, const char *keyword,
649 HintKeyword hint_keyword)
651 JoinMethodHint *hint;
653 hint = palloc(sizeof(JoinMethodHint));
654 hint->base.hint_str = hint_str;
655 hint->base.keyword = keyword;
656 hint->base.hint_keyword = hint_keyword;
657 hint->base.type = HINT_TYPE_JOIN_METHOD;
658 hint->base.state = HINT_STATE_NOTUSED;
659 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
660 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
661 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
662 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
664 hint->inner_nrels = 0;
665 hint->relnames = NULL;
666 hint->enforce_mask = 0;
667 hint->joinrelids = NULL;
668 hint->inner_joinrelids = NULL;
670 return (Hint *) hint;
674 JoinMethodHintDelete(JoinMethodHint *hint)
683 for (i = 0; i < hint->nrels; i++)
684 pfree(hint->relnames[i]);
685 pfree(hint->relnames);
688 bms_free(hint->joinrelids);
689 bms_free(hint->inner_joinrelids);
694 LeadingHintCreate(const char *hint_str, const char *keyword,
695 HintKeyword hint_keyword)
699 hint = palloc(sizeof(LeadingHint));
700 hint->base.hint_str = hint_str;
701 hint->base.keyword = keyword;
702 hint->base.hint_keyword = hint_keyword;
703 hint->base.type = HINT_TYPE_LEADING;
704 hint->base.state = HINT_STATE_NOTUSED;
705 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
706 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
707 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
708 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
709 hint->relations = NIL;
710 hint->outer_inner = NULL;
712 return (Hint *) hint;
716 LeadingHintDelete(LeadingHint *hint)
721 list_free_deep(hint->relations);
722 if (hint->outer_inner)
723 pfree(hint->outer_inner);
728 SetHintCreate(const char *hint_str, const char *keyword,
729 HintKeyword hint_keyword)
733 hint = palloc(sizeof(SetHint));
734 hint->base.hint_str = hint_str;
735 hint->base.keyword = keyword;
736 hint->base.hint_keyword = hint_keyword;
737 hint->base.type = HINT_TYPE_SET;
738 hint->base.state = HINT_STATE_NOTUSED;
739 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
740 hint->base.desc_func = (HintDescFunction) SetHintDesc;
741 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
742 hint->base.parse_func = (HintParseFunction) SetHintParse;
747 return (Hint *) hint;
751 SetHintDelete(SetHint *hint)
761 list_free(hint->words);
766 RowsHintCreate(const char *hint_str, const char *keyword,
767 HintKeyword hint_keyword)
771 hint = palloc(sizeof(RowsHint));
772 hint->base.hint_str = hint_str;
773 hint->base.keyword = keyword;
774 hint->base.hint_keyword = hint_keyword;
775 hint->base.type = HINT_TYPE_ROWS;
776 hint->base.state = HINT_STATE_NOTUSED;
777 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
778 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
779 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
780 hint->base.parse_func = (HintParseFunction) RowsHintParse;
782 hint->inner_nrels = 0;
783 hint->relnames = NULL;
784 hint->joinrelids = NULL;
785 hint->inner_joinrelids = NULL;
786 hint->value_type = RVT_ABSOLUTE;
789 return (Hint *) hint;
793 RowsHintDelete(RowsHint *hint)
802 for (i = 0; i < hint->nrels; i++)
803 pfree(hint->relnames[i]);
804 pfree(hint->relnames);
807 bms_free(hint->joinrelids);
808 bms_free(hint->inner_joinrelids);
813 HintStateCreate(void)
817 hstate = palloc(sizeof(HintState));
818 hstate->hint_str = NULL;
819 hstate->nall_hints = 0;
820 hstate->max_all_hints = 0;
821 hstate->all_hints = NULL;
822 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
823 hstate->scan_hints = NULL;
824 hstate->init_scan_mask = 0;
825 hstate->parent_relid = 0;
826 hstate->parent_rel_oid = InvalidOid;
827 hstate->parent_hint = NULL;
828 hstate->parent_index_infos = NIL;
829 hstate->join_hints = NULL;
830 hstate->init_join_mask = 0;
831 hstate->join_hint_level = NULL;
832 hstate->leading_hint = NULL;
833 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
834 hstate->set_hints = NULL;
835 hstate->rows_hints = NULL;
841 HintStateDelete(HintState *hstate)
848 if (hstate->hint_str)
849 pfree(hstate->hint_str);
851 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
852 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
853 if (hstate->all_hints)
854 pfree(hstate->all_hints);
855 if (hstate->parent_index_infos)
856 list_free(hstate->parent_index_infos);
860 * Copy given value into buf, with quoting with '"' if necessary.
863 quote_value(StringInfo buf, const char *value)
865 bool need_quote = false;
868 for (str = value; *str != '\0'; str++)
870 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
873 appendStringInfoCharMacro(buf, '"');
878 for (str = value; *str != '\0'; str++)
881 appendStringInfoCharMacro(buf, '"');
883 appendStringInfoCharMacro(buf, *str);
887 appendStringInfoCharMacro(buf, '"');
891 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
895 appendStringInfo(buf, "%s(", hint->base.keyword);
896 if (hint->relname != NULL)
898 quote_value(buf, hint->relname);
899 foreach(l, hint->indexnames)
901 appendStringInfoCharMacro(buf, ' ');
902 quote_value(buf, (char *) lfirst(l));
905 appendStringInfoString(buf, ")\n");
909 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
913 appendStringInfo(buf, "%s(", hint->base.keyword);
914 if (hint->relnames != NULL)
916 quote_value(buf, hint->relnames[0]);
917 for (i = 1; i < hint->nrels; i++)
919 appendStringInfoCharMacro(buf, ' ');
920 quote_value(buf, hint->relnames[i]);
923 appendStringInfoString(buf, ")\n");
928 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
930 if (outer_inner->relation == NULL)
937 appendStringInfoCharMacro(buf, '(');
938 foreach(l, outer_inner->outer_inner_pair)
943 appendStringInfoCharMacro(buf, ' ');
945 OuterInnerDesc(lfirst(l), buf);
948 appendStringInfoCharMacro(buf, ')');
951 quote_value(buf, outer_inner->relation);
955 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
957 appendStringInfo(buf, "%s(", HINT_LEADING);
958 if (hint->outer_inner == NULL)
965 foreach(l, hint->relations)
970 appendStringInfoCharMacro(buf, ' ');
972 quote_value(buf, (char *) lfirst(l));
976 OuterInnerDesc(hint->outer_inner, buf);
978 appendStringInfoString(buf, ")\n");
982 SetHintDesc(SetHint *hint, StringInfo buf)
984 bool is_first = true;
987 appendStringInfo(buf, "%s(", HINT_SET);
988 foreach(l, hint->words)
993 appendStringInfoCharMacro(buf, ' ');
995 quote_value(buf, (char *) lfirst(l));
997 appendStringInfo(buf, ")\n");
1001 RowsHintDesc(RowsHint *hint, StringInfo buf)
1005 appendStringInfo(buf, "%s(", hint->base.keyword);
1006 if (hint->relnames != NULL)
1008 quote_value(buf, hint->relnames[0]);
1009 for (i = 1; i < hint->nrels; i++)
1011 appendStringInfoCharMacro(buf, ' ');
1012 quote_value(buf, hint->relnames[i]);
1015 appendStringInfoString(buf, ")\n");
1020 * Append string which represents all hints in a given state to buf, with
1021 * preceding title with them.
1024 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1029 appendStringInfo(buf, "%s:\n", title);
1030 for (i = 0; i < hstate->nall_hints; i++)
1032 if (hstate->all_hints[i]->state != state)
1035 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
1040 * Dump contents of given hstate to server log with log level LOG.
1043 HintStateDump(HintState *hstate)
1049 elog(LOG, "pg_hint_plan:\nno hint");
1053 initStringInfo(&buf);
1055 appendStringInfoString(&buf, "pg_hint_plan:\n");
1056 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
1057 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
1058 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
1059 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
1061 elog(LOG, "%s", buf.data);
1071 RelnameCmp(const void *a, const void *b)
1073 const char *relnamea = *((const char **) a);
1074 const char *relnameb = *((const char **) b);
1076 return strcmp(relnamea, relnameb);
1080 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1082 return RelnameCmp(&a->relname, &b->relname);
1086 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1090 if (a->nrels != b->nrels)
1091 return a->nrels - b->nrels;
1093 for (i = 0; i < a->nrels; i++)
1096 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1104 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1110 SetHintCmp(const SetHint *a, const SetHint *b)
1112 return strcmp(a->name, b->name);
1116 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1120 if (a->nrels != b->nrels)
1121 return a->nrels - b->nrels;
1123 for (i = 0; i < a->nrels; i++)
1126 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1134 HintCmp(const void *a, const void *b)
1136 const Hint *hinta = *((const Hint **) a);
1137 const Hint *hintb = *((const Hint **) b);
1139 if (hinta->type != hintb->type)
1140 return hinta->type - hintb->type;
1141 if (hinta->state == HINT_STATE_ERROR)
1143 if (hintb->state == HINT_STATE_ERROR)
1145 return hinta->cmp_func(hinta, hintb);
1149 * Returns byte offset of hint b from hint a. If hint a was specified before
1150 * b, positive value is returned.
1153 HintCmpWithPos(const void *a, const void *b)
1155 const Hint *hinta = *((const Hint **) a);
1156 const Hint *hintb = *((const Hint **) b);
1159 result = HintCmp(a, b);
1161 result = hinta->hint_str - hintb->hint_str;
1170 parse_keyword(const char *str, StringInfo buf)
1174 while (!isspace(*str) && *str != '(' && *str != '\0')
1175 appendStringInfoCharMacro(buf, *str++);
1181 skip_parenthesis(const char *str, char parenthesis)
1185 if (*str != parenthesis)
1187 if (parenthesis == '(')
1188 hint_ereport(str, ("Opening parenthesis is necessary."));
1189 else if (parenthesis == ')')
1190 hint_ereport(str, ("Closing parenthesis is necessary."));
1201 * Parse a token from str, and store malloc'd copy into word. A token can be
1202 * quoted with '"'. Return value is pointer to unparsed portion of original
1203 * string, or NULL if an error occurred.
1205 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1208 parse_quoted_value(const char *str, char **word, bool truncate)
1213 /* Skip leading spaces. */
1216 initStringInfo(&buf);
1229 /* Double quotation must be closed. */
1233 hint_ereport(str, ("Unterminated quoted string."));
1238 * Skip escaped double quotation.
1240 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1241 * block comments) to be an object name, so users must specify
1242 * alias for such object names.
1244 * Those special names can be allowed if we care escaped slashes
1245 * and asterisks, but we don't.
1254 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1258 appendStringInfoCharMacro(&buf, *str++);
1263 hint_ereport(str, ("Zero-length delimited string."));
1270 /* Truncate name if it's too long */
1272 truncate_identifier(buf.data, strlen(buf.data), true);
1279 static OuterInnerRels *
1280 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1282 OuterInnerRels *outer_inner;
1284 outer_inner = palloc(sizeof(OuterInnerRels));
1285 outer_inner->relation = name;
1286 outer_inner->outer_inner_pair = outer_inner_list;
1292 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1294 List *outer_inner_pair = NIL;
1296 if ((str = skip_parenthesis(str, '(')) == NULL)
1301 /* Store words in parentheses into outer_inner_list. */
1302 while(*str != ')' && *str != '\0')
1304 OuterInnerRels *outer_inner_rels;
1308 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1316 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1319 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1322 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1327 (str = skip_parenthesis(str, ')')) == NULL)
1329 list_free(outer_inner_pair);
1333 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1339 parse_parentheses_Leading(const char *str, List **name_list,
1340 OuterInnerRels **outer_inner)
1343 bool truncate = true;
1345 if ((str = skip_parenthesis(str, '(')) == NULL)
1351 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1356 /* Store words in parentheses into name_list. */
1357 while(*str != ')' && *str != '\0')
1359 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1361 list_free(*name_list);
1365 *name_list = lappend(*name_list, name);
1370 if ((str = skip_parenthesis(str, ')')) == NULL)
1376 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1379 bool truncate = true;
1381 if ((str = skip_parenthesis(str, '(')) == NULL)
1386 /* Store words in parentheses into name_list. */
1387 while(*str != ')' && *str != '\0')
1389 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1391 list_free(*name_list);
1395 *name_list = lappend(*name_list, name);
1398 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1399 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1400 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1401 keyword == HINT_KEYWORD_SET)
1407 if ((str = skip_parenthesis(str, ')')) == NULL)
1413 parse_hints(HintState *hstate, Query *parse, const char *str)
1418 initStringInfo(&buf);
1419 while (*str != '\0')
1421 const HintParser *parser;
1423 /* in error message, we output the comment including the keyword. */
1424 head = (char *) str;
1426 /* parse only the keyword of the hint. */
1427 resetStringInfo(&buf);
1428 str = parse_keyword(str, &buf);
1430 for (parser = parsers; parser->keyword != NULL; parser++)
1432 char *keyword = parser->keyword;
1435 if (strcasecmp(buf.data, keyword) != 0)
1438 hint = parser->create_func(head, keyword, parser->hint_keyword);
1440 /* parser of each hint does parse in a parenthesis. */
1441 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1443 hint->delete_func(hint);
1449 * Add hint information into all_hints array. If we don't have
1450 * enough space, double the array.
1452 if (hstate->nall_hints == 0)
1454 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1455 hstate->all_hints = (Hint **)
1456 palloc(sizeof(Hint *) * hstate->max_all_hints);
1458 else if (hstate->nall_hints == hstate->max_all_hints)
1460 hstate->max_all_hints *= 2;
1461 hstate->all_hints = (Hint **)
1462 repalloc(hstate->all_hints,
1463 sizeof(Hint *) * hstate->max_all_hints);
1466 hstate->all_hints[hstate->nall_hints] = hint;
1467 hstate->nall_hints++;
1474 if (parser->keyword == NULL)
1477 ("Unrecognized hint keyword \"%s\".", buf.data));
1488 * Get hints from table by client-supplied query string and application name.
1491 get_hints_from_table(const char *client_query, const char *client_application)
1493 const char *search_query =
1495 " FROM hint_plan.hints "
1496 " WHERE norm_query_string = $1 "
1497 " AND ( application_name = $2 "
1498 " OR application_name = '' ) "
1499 " ORDER BY application_name DESC";
1500 static SPIPlanPtr plan = NULL;
1502 Oid argtypes[2] = { TEXTOID, TEXTOID };
1504 bool nulls[2] = { false, false };
1517 p = SPI_prepare(search_query, 2, argtypes);
1518 plan = SPI_saveplan(p);
1522 qry = cstring_to_text(client_query);
1523 app = cstring_to_text(client_application);
1524 values[0] = PointerGetDatum(qry);
1525 values[1] = PointerGetDatum(app);
1527 SPI_execute_plan(plan, values, nulls, true, 1);
1529 if (SPI_processed > 0)
1533 hints = SPI_getvalue(SPI_tuptable->vals[0],
1534 SPI_tuptable->tupdesc, 1);
1536 * Here we use SPI_palloc to ensure that hints string is valid even
1537 * after SPI_finish call. We can't use simple palloc because it
1538 * allocates memory in SPI's context and that context is deleted in
1541 buf = SPI_palloc(strlen(hints) + 1);
1561 * Get client-supplied query string.
1564 get_query_string(void)
1570 PreparedStatement *entry;
1572 entry = FetchPreparedStatement(stmt_name, true);
1573 p = entry->plansource->query_string;
1575 else if (plpgsql_query_string)
1576 p = plpgsql_query_string;
1578 p = debug_query_string;
1584 * Get hints from the head block comment in client-supplied query string.
1587 get_hints_from_comment(const char *p)
1589 const char *hint_head;
1597 /* extract query head comment. */
1598 hint_head = strstr(p, HINT_START);
1599 if (hint_head == NULL)
1601 for (;p < hint_head; p++)
1604 * Allow these characters precedes hint comment:
1606 * - alphabets which are in ASCII range
1607 * - space, tabs and new-lines
1608 * - underscores, for identifier
1609 * - commas, for SELECT clause, EXPLAIN and PREPARE
1610 * - parentheses, for EXPLAIN and PREPARE
1612 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1613 * avoid behavior which depends on locale setting.
1615 if (!(*p >= '0' && *p <= '9') &&
1616 !(*p >= 'A' && *p <= 'Z') &&
1617 !(*p >= 'a' && *p <= 'z') &&
1621 *p != '(' && *p != ')')
1625 len = strlen(HINT_START);
1630 /* find hint end keyword. */
1631 if ((tail = strstr(p, HINT_END)) == NULL)
1633 hint_ereport(head, ("Unterminated block comment."));
1637 /* We don't support nested block comments. */
1638 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1640 hint_ereport(head, ("Nested block comments are not supported."));
1644 /* Make a copy of hint. */
1646 head = palloc(len + 1);
1647 memcpy(head, p, len);
1655 * Parse hints that got, create hint struct from parse tree and parse hints.
1658 create_hintstate(Query *parse, const char *hints)
1668 hstate = HintStateCreate();
1669 hstate->hint_str = (char *) hints;
1671 /* parse each hint. */
1672 parse_hints(hstate, parse, p);
1674 /* When nothing specified a hint, we free HintState and returns NULL. */
1675 if (hstate->nall_hints == 0)
1677 HintStateDelete(hstate);
1681 /* Sort hints in order of original position. */
1682 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1685 /* Count number of hints per hint-type. */
1686 for (i = 0; i < hstate->nall_hints; i++)
1688 Hint *cur_hint = hstate->all_hints[i];
1689 hstate->num_hints[cur_hint->type]++;
1693 * If an object (or a set of objects) has multiple hints of same hint-type,
1694 * only the last hint is valid and others are ignored in planning.
1695 * Hints except the last are marked as 'duplicated' to remember the order.
1697 for (i = 0; i < hstate->nall_hints - 1; i++)
1699 Hint *cur_hint = hstate->all_hints[i];
1700 Hint *next_hint = hstate->all_hints[i + 1];
1703 * Leading hint is marked as 'duplicated' in transform_join_hints.
1705 if (cur_hint->type == HINT_TYPE_LEADING &&
1706 next_hint->type == HINT_TYPE_LEADING)
1710 * Note that we need to pass addresses of hint pointers, because
1711 * HintCmp is designed to sort array of Hint* by qsort.
1713 if (HintCmp(&cur_hint, &next_hint) == 0)
1715 hint_ereport(cur_hint->hint_str,
1716 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1717 cur_hint->state = HINT_STATE_DUPLICATION;
1722 * Make sure that per-type array pointers point proper position in the
1723 * array which consists of all hints.
1725 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1726 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1727 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1728 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1729 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1730 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1731 hstate->num_hints[HINT_TYPE_LEADING]);
1732 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1733 hstate->num_hints[HINT_TYPE_SET]);
1739 * Parse inside of parentheses of scan-method hints.
1742 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1745 const char *keyword = hint->base.keyword;
1746 HintKeyword hint_keyword = hint->base.hint_keyword;
1747 List *name_list = NIL;
1750 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1753 /* Parse relation name and index name(s) if given hint accepts. */
1754 length = list_length(name_list);
1757 hint->relname = linitial(name_list);
1758 hint->indexnames = list_delete_first(name_list);
1760 /* check whether the hint accepts index name(s). */
1762 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1763 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1764 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1765 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1766 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1767 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1770 ("%s hint accepts only one relation.",
1771 hint->base.keyword));
1772 hint->base.state = HINT_STATE_ERROR;
1779 ("%s hint requires a relation.",
1780 hint->base.keyword));
1781 hint->base.state = HINT_STATE_ERROR;
1785 /* Set a bit for specified hint. */
1786 switch (hint_keyword)
1788 case HINT_KEYWORD_SEQSCAN:
1789 hint->enforce_mask = ENABLE_SEQSCAN;
1791 case HINT_KEYWORD_INDEXSCAN:
1792 hint->enforce_mask = ENABLE_INDEXSCAN;
1794 case HINT_KEYWORD_INDEXSCANREGEXP:
1795 hint->enforce_mask = ENABLE_INDEXSCAN;
1796 hint->regexp = true;
1798 case HINT_KEYWORD_BITMAPSCAN:
1799 hint->enforce_mask = ENABLE_BITMAPSCAN;
1801 case HINT_KEYWORD_BITMAPSCANREGEXP:
1802 hint->enforce_mask = ENABLE_BITMAPSCAN;
1803 hint->regexp = true;
1805 case HINT_KEYWORD_TIDSCAN:
1806 hint->enforce_mask = ENABLE_TIDSCAN;
1808 case HINT_KEYWORD_NOSEQSCAN:
1809 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1811 case HINT_KEYWORD_NOINDEXSCAN:
1812 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1814 case HINT_KEYWORD_NOBITMAPSCAN:
1815 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1817 case HINT_KEYWORD_NOTIDSCAN:
1818 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1820 case HINT_KEYWORD_INDEXONLYSCAN:
1821 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1823 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1824 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1825 hint->regexp = true;
1827 case HINT_KEYWORD_NOINDEXONLYSCAN:
1828 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1831 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1840 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1843 const char *keyword = hint->base.keyword;
1844 HintKeyword hint_keyword = hint->base.hint_keyword;
1845 List *name_list = NIL;
1847 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1850 hint->nrels = list_length(name_list);
1852 if (hint->nrels > 0)
1858 * Transform relation names from list to array to sort them with qsort
1861 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1862 foreach (l, name_list)
1864 hint->relnames[i] = lfirst(l);
1869 list_free(name_list);
1871 /* A join hint requires at least two relations */
1872 if (hint->nrels < 2)
1875 ("%s hint requires at least two relations.",
1876 hint->base.keyword));
1877 hint->base.state = HINT_STATE_ERROR;
1881 /* Sort hints in alphabetical order of relation names. */
1882 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1884 switch (hint_keyword)
1886 case HINT_KEYWORD_NESTLOOP:
1887 hint->enforce_mask = ENABLE_NESTLOOP;
1889 case HINT_KEYWORD_MERGEJOIN:
1890 hint->enforce_mask = ENABLE_MERGEJOIN;
1892 case HINT_KEYWORD_HASHJOIN:
1893 hint->enforce_mask = ENABLE_HASHJOIN;
1895 case HINT_KEYWORD_NONESTLOOP:
1896 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1898 case HINT_KEYWORD_NOMERGEJOIN:
1899 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1901 case HINT_KEYWORD_NOHASHJOIN:
1902 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1905 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1914 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1917 if (outer_inner->outer_inner_pair == NIL)
1919 if (outer_inner->relation)
1925 if (list_length(outer_inner->outer_inner_pair) == 2)
1927 foreach(l, outer_inner->outer_inner_pair)
1929 if (!OuterInnerPairCheck(lfirst(l)))
1940 OuterInnerList(OuterInnerRels *outer_inner)
1942 List *outer_inner_list = NIL;
1944 OuterInnerRels *outer_inner_rels;
1946 foreach(l, outer_inner->outer_inner_pair)
1948 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1950 if (outer_inner_rels->relation != NULL)
1951 outer_inner_list = lappend(outer_inner_list,
1952 outer_inner_rels->relation);
1954 outer_inner_list = list_concat(outer_inner_list,
1955 OuterInnerList(outer_inner_rels));
1957 return outer_inner_list;
1961 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1964 List *name_list = NIL;
1965 OuterInnerRels *outer_inner = NULL;
1967 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1971 if (outer_inner != NULL)
1972 name_list = OuterInnerList(outer_inner);
1974 hint->relations = name_list;
1975 hint->outer_inner = outer_inner;
1977 /* A Leading hint requires at least two relations */
1978 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1980 hint_ereport(hint->base.hint_str,
1981 ("%s hint requires at least two relations.",
1983 hint->base.state = HINT_STATE_ERROR;
1985 else if (hint->outer_inner != NULL &&
1986 !OuterInnerPairCheck(hint->outer_inner))
1988 hint_ereport(hint->base.hint_str,
1989 ("%s hint requires two sets of relations when parentheses nests.",
1991 hint->base.state = HINT_STATE_ERROR;
1998 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2000 List *name_list = NIL;
2002 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2006 hint->words = name_list;
2008 /* We need both name and value to set GUC parameter. */
2009 if (list_length(name_list) == 2)
2011 hint->name = linitial(name_list);
2012 hint->value = lsecond(name_list);
2016 hint_ereport(hint->base.hint_str,
2017 ("%s hint requires name and value of GUC parameter.",
2019 hint->base.state = HINT_STATE_ERROR;
2026 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2029 HintKeyword hint_keyword = hint->base.hint_keyword;
2030 List *name_list = NIL;
2034 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2037 /* Last element must be rows specification */
2038 hint->nrels = list_length(name_list) - 1;
2040 if (hint->nrels > 0)
2046 * Transform relation names from list to array to sort them with qsort
2049 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2050 foreach (l, name_list)
2052 if (hint->nrels <= i)
2054 hint->relnames[i] = lfirst(l);
2059 /* Retieve rows estimation */
2060 rows_str = list_nth(name_list, hint->nrels);
2061 if (rows_str[0] == '+')
2063 hint->value_type = RVT_ADD;
2066 else if (rows_str[0] == '-')
2068 hint->value_type = RVT_SUB;
2071 else if (rows_str[0] == '*')
2073 hint->value_type = RVT_MULTI;
2076 else if (rows_str[0] == '/')
2078 hint->value_type = RVT_DIV;
2083 hint->value_type = RVT_ABSOLUTE;
2085 hint->rows = strtod(rows_str, &end_ptr);
2089 ("%s hint requires valid number as rows estimation.",
2090 hint->base.keyword));
2091 hint->base.state = HINT_STATE_ERROR;
2095 /* A join hint requires at least two relations */
2096 if (hint->nrels < 2)
2099 ("%s hint requires at least two relations.",
2100 hint->base.keyword));
2101 hint->base.state = HINT_STATE_ERROR;
2105 list_free(name_list);
2107 /* Sort relnames in alphabetical order. */
2108 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2114 * set GUC parameter functions
2118 set_config_option_wrapper(const char *name, const char *value,
2119 GucContext context, GucSource source,
2120 GucAction action, bool changeVal, int elevel)
2123 MemoryContext ccxt = CurrentMemoryContext;
2127 result = set_config_option(name, value, context, source,
2128 action, changeVal, 0);
2134 /* Save error info */
2135 MemoryContextSwitchTo(ccxt);
2136 errdata = CopyErrorData();
2139 ereport(elevel, (errcode(errdata->sqlerrcode),
2140 errmsg("%s", errdata->message),
2141 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2142 errdata->hint ? errhint("%s", errdata->hint) : 0));
2143 FreeErrorData(errdata);
2151 set_config_options(SetHint **options, int noptions, GucContext context)
2156 save_nestlevel = NewGUCNestLevel();
2158 for (i = 0; i < noptions; i++)
2160 SetHint *hint = options[i];
2163 if (!hint_state_enabled(hint))
2166 result = set_config_option_wrapper(hint->name, hint->value, context,
2167 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2168 pg_hint_plan_parse_messages);
2170 hint->base.state = HINT_STATE_USED;
2172 hint->base.state = HINT_STATE_ERROR;
2175 return save_nestlevel;
2178 #define SET_CONFIG_OPTION(name, type_bits) \
2179 set_config_option_wrapper((name), \
2180 (mask & (type_bits)) ? "true" : "false", \
2181 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2184 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2188 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2189 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2190 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2192 mask = enforce_mask;
2194 mask = enforce_mask & current_hint->init_scan_mask;
2196 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2197 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2198 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2199 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2200 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2204 set_join_config_options(unsigned char enforce_mask, GucContext context)
2208 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2209 enforce_mask == ENABLE_HASHJOIN)
2210 mask = enforce_mask;
2212 mask = enforce_mask & current_hint->init_join_mask;
2214 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2215 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2216 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2220 * pg_hint_plan hook functions
2224 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2225 ParamListInfo params, bool isTopLevel,
2226 DestReceiver *dest, char *completionTag)
2231 * Use standard planner if pg_hint_plan is disabled or current nesting
2232 * depth is nesting depth of SPI calls.
2234 if (!pg_hint_plan_enable_hint || nested_level > 0)
2236 if (prev_ProcessUtility)
2237 (*prev_ProcessUtility) (parsetree, queryString, params,
2238 isTopLevel, dest, completionTag);
2240 standard_ProcessUtility(parsetree, queryString, params,
2241 isTopLevel, dest, completionTag);
2247 if (IsA(node, ExplainStmt))
2250 * Draw out parse tree of actual query from Query struct of EXPLAIN
2256 stmt = (ExplainStmt *) node;
2258 Assert(IsA(stmt->query, Query));
2259 query = (Query *) stmt->query;
2261 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2262 node = query->utilityStmt;
2266 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2267 * specified to preceding PREPARE command to use it as source of hints.
2269 if (IsA(node, ExecuteStmt))
2273 stmt = (ExecuteStmt *) node;
2274 stmt_name = stmt->name;
2278 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2281 if (IsA(node, CreateTableAsStmt))
2283 CreateTableAsStmt *stmt;
2286 stmt = (CreateTableAsStmt *) node;
2287 Assert(IsA(stmt->query, Query));
2288 query = (Query *) stmt->query;
2290 if (query->commandType == CMD_UTILITY &&
2291 IsA(query->utilityStmt, ExecuteStmt))
2293 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2294 stmt_name = estmt->name;
2302 if (prev_ProcessUtility)
2303 (*prev_ProcessUtility) (parsetree, queryString, params,
2304 isTopLevel, dest, completionTag);
2306 standard_ProcessUtility(parsetree, queryString, params,
2307 isTopLevel, dest, completionTag);
2321 if (prev_ProcessUtility)
2322 (*prev_ProcessUtility) (parsetree, queryString, params,
2323 isTopLevel, dest, completionTag);
2325 standard_ProcessUtility(parsetree, queryString, params,
2326 isTopLevel, dest, completionTag);
2330 * Push a hint into hint stack which is implemented with List struct. Head of
2331 * list is top of stack.
2334 push_hint(HintState *hstate)
2336 /* Prepend new hint to the list means pushing to stack. */
2337 HintStateStack = lcons(hstate, HintStateStack);
2339 /* Pushed hint is the one which should be used hereafter. */
2340 current_hint = hstate;
2343 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2347 /* Hint stack must not be empty. */
2348 if(HintStateStack == NIL)
2349 elog(ERROR, "hint stack is empty");
2352 * Take a hint at the head from the list, and free it. Switch current_hint
2353 * to point new head (NULL if the list is empty).
2355 HintStateStack = list_delete_first(HintStateStack);
2356 HintStateDelete(current_hint);
2357 if(HintStateStack == NIL)
2358 current_hint = NULL;
2360 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2363 static PlannedStmt *
2364 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2366 const char *hints = NULL;
2369 pgssJumbleState jstate;
2372 PlannedStmt *result;
2376 * Use standard planner if pg_hint_plan is disabled or current nesting
2377 * depth is nesting depth of SPI calls. Other hook functions try to change
2378 * plan with current_hint if any, so set it to NULL.
2380 if (!pg_hint_plan_enable_hint || nested_level > 0)
2381 goto standard_planner_proc;
2383 /* Create hint struct from client-supplied query string. */
2384 query = get_query_string();
2387 * Create hintstate from hint specified for the query, if any.
2389 * First we lookup hint in pg_hint.hints table by normalized query string,
2390 * unless pg_hint_plan.enable_hint_table is OFF.
2391 * This parameter provides option to avoid overhead of table lookup during
2394 * If no hint was found, then we try to get hint from special query comment.
2396 if (pg_hint_plan_enable_hint_table)
2399 * Search hint information which is stored for the query and the
2400 * application. Query string is normalized before using in condition
2401 * in order to allow fuzzy matching.
2403 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2404 * careful when supporting PostgreSQL's version up.
2406 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2407 jstate.jumble_len = 0;
2408 jstate.clocations_buf_size = 32;
2409 jstate.clocations = (pgssLocationLen *)
2410 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2411 jstate.clocations_count = 0;
2412 JumbleQuery(&jstate, parse);
2414 * generate_normalized_query() copies exact given query_len bytes, so we
2415 * add 1 byte for null-termination here. As comments on
2416 * generate_normalized_query says, generate_normalized_query doesn't
2417 * take care of null-terminate, but additional 1 byte ensures that '\0'
2418 * byte in the source buffer to be copied into norm_query.
2420 query_len = strlen(query) + 1;
2421 norm_query = generate_normalized_query(&jstate,
2424 GetDatabaseEncoding());
2425 hints = get_hints_from_table(norm_query, application_name);
2427 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2428 norm_query, application_name, hints ? hints : "(none)");
2431 hints = get_hints_from_comment(query);
2432 hstate = create_hintstate(parse, hints);
2435 * Use standard planner if the statement has not valid hint. Other hook
2436 * functions try to change plan with current_hint if any, so set it to
2440 goto standard_planner_proc;
2443 * Push new hint struct to the hint stack to disable previous hint context.
2447 /* Set GUC parameters which are specified with Set hint. */
2448 save_nestlevel = set_config_options(current_hint->set_hints,
2449 current_hint->num_hints[HINT_TYPE_SET],
2450 current_hint->context);
2453 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2454 if (enable_indexscan)
2455 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2456 if (enable_bitmapscan)
2457 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2459 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2460 if (enable_indexonlyscan)
2461 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2462 if (enable_nestloop)
2463 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2464 if (enable_mergejoin)
2465 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2466 if (enable_hashjoin)
2467 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2470 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2471 * state when this planner started when error occurred in planner.
2476 result = (*prev_planner) (parse, cursorOptions, boundParams);
2478 result = standard_planner(parse, cursorOptions, boundParams);
2483 * Rollback changes of GUC parameters, and pop current hint context
2484 * from hint stack to rewind the state.
2486 AtEOXact_GUC(true, save_nestlevel);
2492 /* Print hint in debug mode. */
2493 if (pg_hint_plan_debug_print)
2494 HintStateDump(current_hint);
2497 * Rollback changes of GUC parameters, and pop current hint context from
2498 * hint stack to rewind the state.
2500 AtEOXact_GUC(true, save_nestlevel);
2505 standard_planner_proc:
2506 current_hint = NULL;
2508 return (*prev_planner) (parse, cursorOptions, boundParams);
2510 return standard_planner(parse, cursorOptions, boundParams);
2514 * Return scan method hint which matches given aliasname.
2516 static ScanMethodHint *
2517 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2523 * We can't apply scan method hint if the relation is:
2524 * - not a base relation
2525 * - not an ordinary relation (such as join and subquery)
2527 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2530 rte = root->simple_rte_array[rel->relid];
2532 /* We can't force scan method of foreign tables */
2533 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2536 /* Find scan method hint, which matches given names, from the list. */
2537 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2539 ScanMethodHint *hint = current_hint->scan_hints[i];
2541 /* We ignore disabled hints. */
2542 if (!hint_state_enabled(hint))
2545 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2555 * Returns TRUE on match, FALSE on no match.
2557 * s1 --- the data to match against
2558 * s2 --- the pattern
2560 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2563 regexpeq(const char *s1, const char *s2)
2569 strcpy(name.data, s1);
2570 regexp = cstring_to_text(s2);
2572 result = DirectFunctionCall2Coll(nameregexeq,
2573 DEFAULT_COLLATION_OID,
2574 NameGetDatum(&name),
2575 PointerGetDatum(regexp));
2576 return DatumGetBool(result);
2580 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2588 * We delete all the IndexOptInfo list and prevent you from being usable by
2591 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2592 hint->enforce_mask == ENABLE_TIDSCAN)
2594 list_free_deep(rel->indexlist);
2595 rel->indexlist = NIL;
2596 hint->base.state = HINT_STATE_USED;
2602 * When a list of indexes is not specified, we just use all indexes.
2604 if (hint->indexnames == NIL)
2608 * Leaving only an specified index, we delete it from a IndexOptInfo list
2612 if (pg_hint_plan_debug_print)
2613 initStringInfo(&buf);
2615 for (cell = list_head(rel->indexlist); cell; cell = next)
2617 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2618 char *indexname = get_rel_name(info->indexoid);
2620 bool use_index = false;
2624 foreach(l, hint->indexnames)
2626 char *hintname = (char *) lfirst(l);
2630 result = regexpeq(indexname, hintname);
2632 result = RelnameCmp(&indexname, &hintname) == 0;
2637 if (pg_hint_plan_debug_print)
2639 appendStringInfoCharMacro(&buf, ' ');
2640 quote_value(&buf, indexname);
2648 * to make the index a candidate when definition of this index is
2649 * matched with the index's definition of current_hint.
2651 if (OidIsValid(relationObjectId) && !use_index)
2653 foreach(l, current_hint->parent_index_infos)
2657 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2659 /* check to match the parameter of unique */
2660 if (p_info->indisunique != info->unique)
2663 /* check to match the parameter of index's method */
2664 if (p_info->method != info->relam)
2667 /* to check to match the indexkey's configuration */
2668 if ((list_length(p_info->column_names)) !=
2672 /* check to match the indexkey's configuration */
2673 for (i = 0; i < info->ncolumns; i++)
2675 char *c_attname = NULL;
2676 char *p_attname = NULL;
2679 list_nth(p_info->column_names, i);
2681 /* both are expressions */
2682 if (info->indexkeys[i] == 0 && !p_attname)
2685 /* one's column is expression, the other is not */
2686 if (info->indexkeys[i] == 0 || !p_attname)
2689 c_attname = get_attname(relationObjectId,
2690 info->indexkeys[i]);
2692 if (strcmp(p_attname, c_attname) != 0)
2695 if (p_info->indcollation[i] != info->indexcollations[i])
2698 if (p_info->opclass[i] != info->opcintype[i])
2701 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2702 info->reverse_sort[i])
2705 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2706 info->nulls_first[i])
2711 if (i != info->ncolumns)
2714 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2715 (p_info->indpred_str && (info->indpred != NIL)))
2718 * Fetch the pg_index tuple by the Oid of the index
2720 ht_idx = SearchSysCache1(INDEXRELID,
2721 ObjectIdGetDatum(info->indexoid));
2723 /* check to match the expression's parameter of index */
2724 if (p_info->expression_str &&
2725 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2732 * to change the expression's parameter of child's
2735 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2736 Anum_pg_index_indexprs,
2739 result = DirectFunctionCall2(pg_get_expr,
2744 if (strcmp(p_info->expression_str,
2745 text_to_cstring(DatumGetTextP(result))) != 0)
2748 ReleaseSysCache(ht_idx);
2754 /* Check to match the predicate's parameter of index */
2755 if (p_info->indpred_str &&
2756 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2763 * to change the predicate's parameter of child's
2766 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2767 Anum_pg_index_indpred,
2770 result = DirectFunctionCall2(pg_get_expr,
2775 if (strcmp(p_info->indpred_str,
2776 text_to_cstring(DatumGetTextP(result))) != 0)
2779 ReleaseSysCache(ht_idx);
2786 ReleaseSysCache(ht_idx);
2788 else if (p_info->expression_str || (info->indexprs != NIL))
2790 else if (p_info->indpred_str || (info->indpred != NIL))
2795 /* to log the candidate of index */
2796 if (pg_hint_plan_debug_print)
2798 appendStringInfoCharMacro(&buf, ' ');
2799 quote_value(&buf, indexname);
2807 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2814 if (pg_hint_plan_debug_print)
2817 StringInfoData rel_buf;
2819 if (OidIsValid(relationObjectId))
2820 relname = get_rel_name(relationObjectId);
2822 relname = hint->relname;
2824 initStringInfo(&rel_buf);
2825 quote_value(&rel_buf, relname);
2828 (errmsg("available indexes for %s(%s):%s",
2833 pfree(rel_buf.data);
2838 * Return information of index definition.
2840 static ParentIndexInfo *
2841 get_parent_index_info(Oid indexoid, Oid relid)
2843 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2844 Relation indexRelation;
2845 Form_pg_index index;
2849 indexRelation = index_open(indexoid, RowExclusiveLock);
2851 index = indexRelation->rd_index;
2853 p_info->indisunique = index->indisunique;
2854 p_info->method = indexRelation->rd_rel->relam;
2856 p_info->column_names = NIL;
2857 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2858 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2859 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2861 for (i = 0; i < index->indnatts; i++)
2863 attname = get_attname(relid, index->indkey.values[i]);
2864 p_info->column_names = lappend(p_info->column_names, attname);
2866 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2867 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2868 p_info->indoption[i] = indexRelation->rd_indoption[i];
2872 * to check to match the expression's parameter of index with child indexes
2874 p_info->expression_str = NULL;
2875 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2881 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2882 Anum_pg_index_indexprs, &isnull);
2884 result = DirectFunctionCall2(pg_get_expr,
2886 ObjectIdGetDatum(relid));
2888 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2892 * to check to match the predicate's parameter of index with child indexes
2894 p_info->indpred_str = NULL;
2895 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2901 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2902 Anum_pg_index_indpred, &isnull);
2904 result = DirectFunctionCall2(pg_get_expr,
2906 ObjectIdGetDatum(relid));
2908 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2911 index_close(indexRelation, NoLock);
2917 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2918 bool inhparent, RelOptInfo *rel)
2920 ScanMethodHint *hint;
2922 if (prev_get_relation_info)
2923 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2926 * Do nothing if we don't have valid hint in this context or current
2927 * nesting depth is nesting depth of SPI calls.
2929 if (!current_hint || nested_level > 0)
2934 /* store does relids of parent table. */
2935 current_hint->parent_relid = rel->relid;
2936 current_hint->parent_rel_oid = relationObjectId;
2938 else if (current_hint->parent_relid != 0)
2941 * We use the same GUC parameter if this table is the child table of a
2942 * table called pg_hint_plan_get_relation_info just before that.
2946 /* append_rel_list contains all append rels; ignore others */
2947 foreach(l, root->append_rel_list)
2949 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2951 /* This rel is child table. */
2952 if (appinfo->parent_relid == current_hint->parent_relid &&
2953 appinfo->child_relid == rel->relid)
2955 if (current_hint->parent_hint)
2956 delete_indexes(current_hint->parent_hint, rel,
2963 /* This rel is not inherit table. */
2964 current_hint->parent_relid = 0;
2965 current_hint->parent_rel_oid = InvalidOid;
2966 current_hint->parent_hint = NULL;
2970 * If scan method hint was given, reset GUC parameters which control
2971 * planner behavior about choosing scan methods.
2973 if ((hint = find_scan_hint(root, rel)) == NULL)
2975 set_scan_config_options(current_hint->init_scan_mask,
2976 current_hint->context);
2979 set_scan_config_options(hint->enforce_mask, current_hint->context);
2980 hint->base.state = HINT_STATE_USED;
2988 current_hint->parent_hint = hint;
2990 relation = heap_open(relationObjectId, NoLock);
2991 indexoidlist = RelationGetIndexList(relation);
2993 foreach(l, indexoidlist)
2995 Oid indexoid = lfirst_oid(l);
2996 char *indexname = get_rel_name(indexoid);
2997 bool use_index = false;
2999 ParentIndexInfo *parent_index_info;
3001 foreach(lc, hint->indexnames)
3003 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3012 parent_index_info = get_parent_index_info(indexoid,
3014 current_hint->parent_index_infos =
3015 lappend(current_hint->parent_index_infos, parent_index_info);
3017 heap_close(relation, NoLock);
3020 delete_indexes(hint, rel, InvalidOid);
3024 * Return index of relation which matches given aliasname, or 0 if not found.
3025 * If same aliasname was used multiple times in a query, return -1.
3028 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3034 for (i = 1; i < root->simple_rel_array_size; i++)
3038 if (root->simple_rel_array[i] == NULL)
3041 Assert(i == root->simple_rel_array[i]->relid);
3043 if (RelnameCmp(&aliasname,
3044 &root->simple_rte_array[i]->eref->aliasname) != 0)
3047 foreach(l, initial_rels)
3049 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3051 if (rel->reloptkind == RELOPT_BASEREL)
3053 if (rel->relid != i)
3058 Assert(rel->reloptkind == RELOPT_JOINREL);
3060 if (!bms_is_member(i, rel->relids))
3067 ("Relation name \"%s\" is ambiguous.",
3082 * Return join hint which matches given joinrelids.
3084 static JoinMethodHint *
3085 find_join_hint(Relids joinrelids)
3090 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3092 foreach(l, join_hint)
3094 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3096 if (bms_equal(joinrelids, hint->joinrelids))
3104 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3105 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3107 OuterInnerRels *outer_rels;
3108 OuterInnerRels *inner_rels;
3109 Relids outer_relids;
3110 Relids inner_relids;
3112 JoinMethodHint *hint;
3114 if (outer_inner->relation != NULL)
3116 return bms_make_singleton(
3117 find_relid_aliasname(root, outer_inner->relation,
3119 leading_hint->base.hint_str));
3122 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3123 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3125 outer_relids = OuterInnerJoinCreate(outer_rels,
3131 inner_relids = OuterInnerJoinCreate(inner_rels,
3138 join_relids = bms_add_members(outer_relids, inner_relids);
3140 if (bms_num_members(join_relids) > nbaserel)
3144 * If we don't have join method hint, create new one for the
3145 * join combination with all join methods are enabled.
3147 hint = find_join_hint(join_relids);
3151 * Here relnames is not set, since Relids bitmap is sufficient to
3152 * control paths of this query afterward.
3154 hint = (JoinMethodHint *) JoinMethodHintCreate(
3155 leading_hint->base.hint_str,
3157 HINT_KEYWORD_LEADING);
3158 hint->base.state = HINT_STATE_USED;
3159 hint->nrels = bms_num_members(join_relids);
3160 hint->enforce_mask = ENABLE_ALL_JOIN;
3161 hint->joinrelids = bms_copy(join_relids);
3162 hint->inner_nrels = bms_num_members(inner_relids);
3163 hint->inner_joinrelids = bms_copy(inner_relids);
3165 hstate->join_hint_level[hint->nrels] =
3166 lappend(hstate->join_hint_level[hint->nrels], hint);
3170 hint->inner_nrels = bms_num_members(inner_relids);
3171 hint->inner_joinrelids = bms_copy(inner_relids);
3178 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3179 int nrels, char **relnames)
3182 Relids relids = NULL;
3186 for (j = 0; j < nrels; j++)
3188 relname = relnames[j];
3190 relid = find_relid_aliasname(root, relname, initial_rels,
3194 base->state = HINT_STATE_ERROR;
3199 if (bms_is_member(relid, relids))
3201 hint_ereport(base->hint_str,
3202 ("Relation name \"%s\" is duplicated.", relname));
3203 base->state = HINT_STATE_ERROR;
3207 relids = bms_add_member(relids, relid);
3212 * Transform join method hint into handy form.
3214 * - create bitmap of relids from alias names, to make it easier to check
3215 * whether a join path matches a join method hint.
3216 * - add join method hints which are necessary to enforce join order
3217 * specified by Leading hint
3220 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3221 List *initial_rels, JoinMethodHint **join_method_hints)
3229 LeadingHint *lhint = NULL;
3232 * Create bitmap of relids from alias names for each join method hint.
3233 * Bitmaps are more handy than strings in join searching.
3235 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3237 JoinMethodHint *hint = hstate->join_hints[i];
3239 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3242 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3243 initial_rels, hint->nrels, hint->relnames);
3245 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3248 hstate->join_hint_level[hint->nrels] =
3249 lappend(hstate->join_hint_level[hint->nrels], hint);
3253 * Create bitmap of relids from alias names for each rows hint.
3254 * Bitmaps are more handy than strings in join searching.
3256 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3258 RowsHint *hint = hstate->rows_hints[i];
3260 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3263 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3264 initial_rels, hint->nrels, hint->relnames);
3266 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3270 /* Do nothing if no Leading hint was supplied. */
3271 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3275 * Decide to use Leading hint。
3277 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3279 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3282 if (leading_hint->base.state == HINT_STATE_ERROR)
3288 foreach(l, leading_hint->relations)
3290 relname = (char *)lfirst(l);;
3292 relid = find_relid_aliasname(root, relname, initial_rels,
3293 leading_hint->base.hint_str);
3295 leading_hint->base.state = HINT_STATE_ERROR;
3300 if (bms_is_member(relid, relids))
3302 hint_ereport(leading_hint->base.hint_str,
3303 ("Relation name \"%s\" is duplicated.", relname));
3304 leading_hint->base.state = HINT_STATE_ERROR;
3308 relids = bms_add_member(relids, relid);
3311 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3316 hint_ereport(lhint->base.hint_str,
3317 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3318 lhint->base.state = HINT_STATE_DUPLICATION;
3320 leading_hint->base.state = HINT_STATE_USED;
3321 lhint = leading_hint;
3324 /* check to exist Leading hint marked with 'used'. */
3329 * We need join method hints which fit specified join order in every join
3330 * level. For example, Leading(A B C) virtually requires following join
3331 * method hints, if no join method hint supplied:
3333 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3334 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3336 * If we already have join method hint which fits specified join order in
3337 * that join level, we leave it as-is and don't add new hints.
3341 if (lhint->outer_inner == NULL)
3343 foreach(l, lhint->relations)
3345 JoinMethodHint *hint;
3347 relname = (char *)lfirst(l);
3350 * Find relid of the relation which has given name. If we have the
3351 * name given in Leading hint multiple times in the join, nothing to
3354 relid = find_relid_aliasname(root, relname, initial_rels,
3357 /* Create bitmap of relids for current join level. */
3358 joinrelids = bms_add_member(joinrelids, relid);
3361 /* We never have join method hint for single relation. */
3366 * If we don't have join method hint, create new one for the
3367 * join combination with all join methods are enabled.
3369 hint = find_join_hint(joinrelids);
3373 * Here relnames is not set, since Relids bitmap is sufficient
3374 * to control paths of this query afterward.
3376 hint = (JoinMethodHint *) JoinMethodHintCreate(
3377 lhint->base.hint_str,
3379 HINT_KEYWORD_LEADING);
3380 hint->base.state = HINT_STATE_USED;
3381 hint->nrels = njoinrels;
3382 hint->enforce_mask = ENABLE_ALL_JOIN;
3383 hint->joinrelids = bms_copy(joinrelids);
3386 join_method_hints[njoinrels] = hint;
3388 if (njoinrels >= nbaserel)
3391 bms_free(joinrelids);
3397 * Delete all join hints which have different combination from Leading
3400 for (i = 2; i <= njoinrels; i++)
3402 list_free(hstate->join_hint_level[i]);
3404 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3409 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3416 njoinrels = bms_num_members(joinrelids);
3417 Assert(njoinrels >= 2);
3420 * Delete all join hints which have different combination from Leading
3423 for (i = 2;i <= njoinrels; i++)
3425 if (hstate->join_hint_level[i] != NIL)
3427 ListCell *prev = NULL;
3428 ListCell *next = NULL;
3429 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3431 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3435 if (hint->inner_nrels == 0 &&
3436 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3437 bms_equal(bms_union(hint->joinrelids, joinrelids),
3440 hstate->join_hint_level[i] =
3441 list_delete_cell(hstate->join_hint_level[i], l,
3450 bms_free(joinrelids);
3453 if (hint_state_enabled(lhint))
3455 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3462 * set_plain_rel_pathlist
3463 * Build access paths for a plain relation (no subquery, no inheritance)
3465 * This function was copied and edited from set_plain_rel_pathlist() in
3466 * src/backend/optimizer/path/allpaths.c
3469 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3471 /* Consider sequential scan */
3472 add_path(rel, create_seqscan_path(root, rel, NULL));
3474 /* Consider index scans */
3475 create_index_paths(root, rel);
3477 /* Consider TID scans */
3478 create_tidscan_paths(root, rel);
3480 /* Now find the cheapest of the paths for this rel */
3485 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3490 foreach(l, initial_rels)
3492 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3494 ScanMethodHint *hint;
3496 /* Skip relations which we can't choose scan method. */
3497 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3500 rte = root->simple_rte_array[rel->relid];
3502 /* We can't force scan method of foreign tables */
3503 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3507 * Create scan paths with GUC parameters which are at the beginning of
3508 * planner if scan method hint is not specified, otherwise use
3509 * specified hints and mark the hint as used.
3511 if ((hint = find_scan_hint(root, rel)) == NULL)
3512 set_scan_config_options(hstate->init_scan_mask,
3516 set_scan_config_options(hint->enforce_mask, hstate->context);
3517 hint->base.state = HINT_STATE_USED;
3520 list_free_deep(rel->pathlist);
3521 rel->pathlist = NIL;
3524 /* It's an "append relation", process accordingly */
3525 set_append_rel_pathlist(root, rel, rel->relid, rte);
3529 set_plain_rel_pathlist(root, rel, rte);
3534 * Restore the GUC variables we set above.
3536 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3540 * wrapper of make_join_rel()
3542 * call make_join_rel() after changing enable_* parameters according to given
3546 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3549 JoinMethodHint *hint;
3553 joinrelids = bms_union(rel1->relids, rel2->relids);
3554 hint = find_join_hint(joinrelids);
3555 bms_free(joinrelids);
3558 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3560 if (hint->inner_nrels == 0)
3562 save_nestlevel = NewGUCNestLevel();
3564 set_join_config_options(hint->enforce_mask, current_hint->context);
3566 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3567 hint->base.state = HINT_STATE_USED;
3570 * Restore the GUC variables we set above.
3572 AtEOXact_GUC(true, save_nestlevel);
3575 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3584 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3585 RelOptInfo *joinrel,
3586 RelOptInfo *outerrel,
3587 RelOptInfo *innerrel,
3589 SpecialJoinInfo *sjinfo,
3592 ScanMethodHint *scan_hint = NULL;
3594 JoinMethodHint *join_hint;
3597 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3599 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3600 scan_hint->base.state = HINT_STATE_USED;
3603 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3605 join_hint = find_join_hint(joinrelids);
3606 bms_free(joinrelids);
3608 if (join_hint && join_hint->inner_nrels != 0)
3610 save_nestlevel = NewGUCNestLevel();
3612 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3615 set_join_config_options(join_hint->enforce_mask,
3616 current_hint->context);
3618 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3619 sjinfo, restrictlist);
3620 join_hint->base.state = HINT_STATE_USED;
3624 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3625 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3626 sjinfo, restrictlist);
3630 * Restore the GUC variables we set above.
3632 AtEOXact_GUC(true, save_nestlevel);
3635 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3636 sjinfo, restrictlist);
3638 if (scan_hint != NULL)
3639 set_scan_config_options(current_hint->init_scan_mask,
3640 current_hint->context);
3644 get_num_baserels(List *initial_rels)
3649 foreach(l, initial_rels)
3651 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3653 if (rel->reloptkind == RELOPT_BASEREL)
3655 else if (rel->reloptkind ==RELOPT_JOINREL)
3656 nbaserel+= bms_num_members(rel->relids);
3659 /* other values not expected here */
3660 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3668 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3671 JoinMethodHint **join_method_hints;
3675 bool leading_hint_enable;
3678 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3679 * valid hint is supplied or current nesting depth is nesting depth of SPI
3682 if (!current_hint || nested_level > 0)
3684 if (prev_join_search)
3685 return (*prev_join_search) (root, levels_needed, initial_rels);
3686 else if (enable_geqo && levels_needed >= geqo_threshold)
3687 return geqo(root, levels_needed, initial_rels);
3689 return standard_join_search(root, levels_needed, initial_rels);
3692 /* We apply scan method hint rebuild scan path. */
3693 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3696 * In the case using GEQO, only scan method hints and Set hints have
3697 * effect. Join method and join order is not controllable by hints.
3699 if (enable_geqo && levels_needed >= geqo_threshold)
3700 return geqo(root, levels_needed, initial_rels);
3702 nbaserel = get_num_baserels(initial_rels);
3703 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3704 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3706 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3707 initial_rels, join_method_hints);
3709 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3711 for (i = 2; i <= nbaserel; i++)
3713 list_free(current_hint->join_hint_level[i]);
3715 /* free Leading hint only */
3716 if (join_method_hints[i] != NULL &&
3717 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3718 JoinMethodHintDelete(join_method_hints[i]);
3720 pfree(current_hint->join_hint_level);
3721 pfree(join_method_hints);
3723 if (leading_hint_enable)
3724 set_join_config_options(current_hint->init_join_mask,
3725 current_hint->context);
3732 * Build access paths for a base relation
3734 * This function was copied and edited from set_rel_pathlist() in
3735 * src/backend/optimizer/path/allpaths.c
3738 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3739 Index rti, RangeTblEntry *rte)
3741 if (IS_DUMMY_REL(rel))
3743 /* We already proved the relation empty, so nothing more to do */
3747 /* It's an "append relation", process accordingly */
3748 set_append_rel_pathlist(root, rel, rti, rte);
3752 if (rel->rtekind == RTE_RELATION)
3754 if (rte->relkind == RELKIND_RELATION)
3756 /* Plain relation */
3757 set_plain_rel_pathlist(root, rel, rte);
3760 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3763 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3768 * stmt_beg callback is called when each query in PL/pgSQL function is about
3769 * to be executed. At that timing, we save query string in the global variable
3770 * plpgsql_query_string to use it in planner hook. It's safe to use one global
3771 * variable for the purpose, because its content is only necessary until
3772 * planner hook is called for the query, so recursive PL/pgSQL function calls
3773 * don't harm this mechanism.
3776 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3778 PLpgSQL_expr *expr = NULL;
3780 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
3782 case PLPGSQL_STMT_FORS:
3783 expr = ((PLpgSQL_stmt_fors *) stmt)->query;
3785 case PLPGSQL_STMT_FORC:
3786 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_forc *)stmt)->curvar]))->cursor_explicit_expr;
3788 case PLPGSQL_STMT_RETURN_QUERY:
3789 if (((PLpgSQL_stmt_return_query *) stmt)->query != NULL)
3790 expr = ((PLpgSQL_stmt_return_query *) stmt)->query;
3792 expr = ((PLpgSQL_stmt_return_query *) stmt)->dynquery;
3794 case PLPGSQL_STMT_EXECSQL:
3795 expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3797 case PLPGSQL_STMT_DYNEXECUTE:
3798 expr = ((PLpgSQL_stmt_dynexecute *) stmt)->query;
3800 case PLPGSQL_STMT_DYNFORS:
3801 expr = ((PLpgSQL_stmt_dynfors *) stmt)->query;
3803 case PLPGSQL_STMT_OPEN:
3804 if (((PLpgSQL_stmt_open *) stmt)->query != NULL)
3805 expr = ((PLpgSQL_stmt_open *) stmt)->query;
3806 else if (((PLpgSQL_stmt_open *) stmt)->dynquery != NULL)
3807 expr = ((PLpgSQL_stmt_open *) stmt)->dynquery;
3809 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_open *)stmt)->curvar]))->cursor_explicit_expr;
3816 plpgsql_query_string = expr->query;
3820 * stmt_end callback is called then each query in PL/pgSQL function has
3821 * finished. At that timing, we clear plpgsql_query_string to tell planner
3822 * hook that next call is not for a query written in PL/pgSQL block.
3825 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3827 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3828 plpgsql_query_string = NULL;
3831 #define standard_join_search pg_hint_plan_standard_join_search
3832 #define join_search_one_level pg_hint_plan_join_search_one_level
3833 #define make_join_rel make_join_rel_wrapper
3836 #undef make_join_rel
3837 #define make_join_rel pg_hint_plan_make_join_rel
3838 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3839 #include "make_join_rel.c"
3841 #include "pg_stat_statements.c"