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"
57 #include "access/htup_details.h"
59 #ifdef PG_MODULE_MAGIC
63 #define BLOCK_COMMENT_START "/*"
64 #define BLOCK_COMMENT_END "*/"
65 #define HINT_COMMENT_KEYWORD "+"
66 #define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
67 #define HINT_END BLOCK_COMMENT_END
70 #define HINT_SEQSCAN "SeqScan"
71 #define HINT_INDEXSCAN "IndexScan"
72 #define HINT_INDEXSCANREGEXP "IndexScanRegexp"
73 #define HINT_BITMAPSCAN "BitmapScan"
74 #define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
75 #define HINT_TIDSCAN "TidScan"
76 #define HINT_NOSEQSCAN "NoSeqScan"
77 #define HINT_NOINDEXSCAN "NoIndexScan"
78 #define HINT_NOBITMAPSCAN "NoBitmapScan"
79 #define HINT_NOTIDSCAN "NoTidScan"
80 #define HINT_INDEXONLYSCAN "IndexOnlyScan"
81 #define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
82 #define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
83 #define HINT_NESTLOOP "NestLoop"
84 #define HINT_MERGEJOIN "MergeJoin"
85 #define HINT_HASHJOIN "HashJoin"
86 #define HINT_NONESTLOOP "NoNestLoop"
87 #define HINT_NOMERGEJOIN "NoMergeJoin"
88 #define HINT_NOHASHJOIN "NoHashJoin"
89 #define HINT_LEADING "Leading"
90 #define HINT_SET "Set"
91 #define HINT_ROWS "Rows"
93 #define HINT_ARRAY_DEFAULT_INITSIZE 8
95 #define hint_ereport(str, detail) \
96 ereport(pg_hint_plan_parse_messages, \
97 (errmsg("hint syntax error at or near \"%s\"", (str)), \
100 #define skip_space(str) \
101 while (isspace(*str)) \
106 ENABLE_SEQSCAN = 0x01,
107 ENABLE_INDEXSCAN = 0x02,
108 ENABLE_BITMAPSCAN = 0x04,
109 ENABLE_TIDSCAN = 0x08,
110 ENABLE_INDEXONLYSCAN = 0x10
115 ENABLE_NESTLOOP = 0x01,
116 ENABLE_MERGEJOIN = 0x02,
117 ENABLE_HASHJOIN = 0x04
120 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
121 ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
122 ENABLE_INDEXONLYSCAN)
123 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
124 #define DISABLE_ALL_SCAN 0
125 #define DISABLE_ALL_JOIN 0
127 /* hint keyword of enum type*/
128 typedef enum HintKeyword
130 HINT_KEYWORD_SEQSCAN,
131 HINT_KEYWORD_INDEXSCAN,
132 HINT_KEYWORD_INDEXSCANREGEXP,
133 HINT_KEYWORD_BITMAPSCAN,
134 HINT_KEYWORD_BITMAPSCANREGEXP,
135 HINT_KEYWORD_TIDSCAN,
136 HINT_KEYWORD_NOSEQSCAN,
137 HINT_KEYWORD_NOINDEXSCAN,
138 HINT_KEYWORD_NOBITMAPSCAN,
139 HINT_KEYWORD_NOTIDSCAN,
140 HINT_KEYWORD_INDEXONLYSCAN,
141 HINT_KEYWORD_INDEXONLYSCANREGEXP,
142 HINT_KEYWORD_NOINDEXONLYSCAN,
143 HINT_KEYWORD_NESTLOOP,
144 HINT_KEYWORD_MERGEJOIN,
145 HINT_KEYWORD_HASHJOIN,
146 HINT_KEYWORD_NONESTLOOP,
147 HINT_KEYWORD_NOMERGEJOIN,
148 HINT_KEYWORD_NOHASHJOIN,
149 HINT_KEYWORD_LEADING,
152 HINT_KEYWORD_UNRECOGNIZED
155 typedef struct Hint Hint;
156 typedef struct HintState HintState;
158 typedef Hint *(*HintCreateFunction) (const char *hint_str,
160 HintKeyword hint_keyword);
161 typedef void (*HintDeleteFunction) (Hint *hint);
162 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
163 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
164 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
165 Query *parse, const char *str);
168 #define NUM_HINT_TYPE 5
169 typedef enum HintType
171 HINT_TYPE_SCAN_METHOD,
172 HINT_TYPE_JOIN_METHOD,
178 static const char *HintTypeName[] = {
187 typedef enum HintStatus
189 HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
190 HINT_STATE_USED, /* hint is used */
191 HINT_STATE_DUPLICATION, /* specified hint duplication */
192 HINT_STATE_ERROR /* execute error (parse error does not include
196 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
197 (hint)->base.state == HINT_STATE_USED)
199 /* common data for all hints. */
202 const char *hint_str; /* must not do pfree */
203 const char *keyword; /* must not do pfree */
204 HintKeyword hint_keyword;
207 HintDeleteFunction delete_func;
208 HintDescFunction desc_func;
209 HintCmpFunction cmp_func;
210 HintParseFunction parse_func;
213 /* scan method hints */
214 typedef struct ScanMethodHint
220 unsigned char enforce_mask;
223 typedef struct ParentIndexInfo
228 char *expression_str;
235 /* join method hints */
236 typedef struct JoinMethodHint
242 unsigned char enforce_mask;
244 Relids inner_joinrelids;
247 /* join order hints */
248 typedef struct OuterInnerRels
251 List *outer_inner_pair;
254 typedef struct LeadingHint
257 List *relations; /* relation names specified in Leading hint */
258 OuterInnerRels *outer_inner;
261 /* change a run-time parameter hints */
262 typedef struct SetHint
265 char *name; /* name of variable */
271 typedef enum RowsValueType {
272 RVT_ABSOLUTE, /* Rows(... #1000) */
273 RVT_ADD, /* Rows(... +1000) */
274 RVT_SUB, /* Rows(... -1000) */
275 RVT_MULTI, /* Rows(... *1.2) */
277 typedef struct RowsHint
284 Relids inner_joinrelids;
286 RowsValueType value_type;
291 * Describes a context of hint processing.
295 char *hint_str; /* original hint string */
298 int nall_hints; /* # of valid all hints */
299 int max_all_hints; /* # of slots for all hints */
300 Hint **all_hints; /* parsed all hints */
302 /* # of each hints */
303 int num_hints[NUM_HINT_TYPE];
305 /* for scan method hints */
306 ScanMethodHint **scan_hints; /* parsed scan hints */
307 int init_scan_mask; /* initial value scan parameter */
308 Index parent_relid; /* inherit parent table relid */
309 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
310 List *parent_index_infos; /* information of inherit parent table's
313 /* for join method hints */
314 JoinMethodHint **join_hints; /* parsed join hints */
315 int init_join_mask; /* initial value join parameter */
316 List **join_hint_level;
318 /* for Leading hint */
319 LeadingHint **leading_hint; /* parsed Leading hints */
322 SetHint **set_hints; /* parsed Set hints */
323 GucContext context; /* which GUC parameters can we set? */
326 RowsHint **rows_hints; /* parsed Rows hints */
330 * Describes a hint parser module which is bound with particular hint keyword.
332 typedef struct HintParser
335 HintCreateFunction create_func;
336 HintKeyword hint_keyword;
339 /* Module callbacks */
343 static void push_hint(HintState *hstate);
344 static void pop_hint(void);
346 static void pg_hint_plan_ProcessUtility(Node *parsetree,
347 const char *queryString,
348 ProcessUtilityContext context,
349 ParamListInfo params,
350 DestReceiver *dest, char *completionTag);
351 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
352 ParamListInfo boundParams);
353 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
354 Oid relationObjectId,
355 bool inhparent, RelOptInfo *rel);
356 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
360 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
361 HintKeyword hint_keyword);
362 static void ScanMethodHintDelete(ScanMethodHint *hint);
363 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
364 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
365 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
366 Query *parse, const char *str);
367 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
368 HintKeyword hint_keyword);
369 static void JoinMethodHintDelete(JoinMethodHint *hint);
370 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
371 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
372 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
373 Query *parse, const char *str);
374 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
375 HintKeyword hint_keyword);
376 static void LeadingHintDelete(LeadingHint *hint);
377 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
378 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
379 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
380 Query *parse, const char *str);
381 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
382 HintKeyword hint_keyword);
383 static void SetHintDelete(SetHint *hint);
384 static void SetHintDesc(SetHint *hint, StringInfo buf);
385 static int SetHintCmp(const SetHint *a, const SetHint *b);
386 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
388 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
389 HintKeyword hint_keyword);
390 static void RowsHintDelete(RowsHint *hint);
391 static void RowsHintDesc(RowsHint *hint, StringInfo buf);
392 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
393 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
394 Query *parse, const char *str);
395 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
396 HintKeyword hint_keyword);
398 static void quote_value(StringInfo buf, const char *value);
400 static const char *parse_quoted_value(const char *str, char **word,
403 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
406 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
407 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
408 ListCell *other_rels);
409 static void make_rels_by_clauseless_joins(PlannerInfo *root,
411 ListCell *other_rels);
412 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
413 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
414 Index rti, RangeTblEntry *rte);
415 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
416 List *live_childrels,
417 List *all_child_pathkeys);
418 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
420 Relids required_outer);
421 static List *accumulate_append_subpath(List *subpaths, Path *path);
422 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
425 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
427 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
431 static bool pg_hint_plan_enable_hint = true;
432 static bool pg_hint_plan_debug_print = false;
433 static int pg_hint_plan_parse_messages = INFO;
434 /* Default is off, to keep backward compatibility. */
435 static bool pg_hint_plan_enable_hint_table = false;
437 static const struct config_enum_entry parse_messages_level_options[] = {
438 {"debug", DEBUG2, true},
439 {"debug5", DEBUG5, false},
440 {"debug4", DEBUG4, false},
441 {"debug3", DEBUG3, false},
442 {"debug2", DEBUG2, false},
443 {"debug1", DEBUG1, false},
445 {"info", INFO, false},
446 {"notice", NOTICE, false},
447 {"warning", WARNING, false},
448 {"error", ERROR, false},
450 * {"fatal", FATAL, true},
451 * {"panic", PANIC, true},
456 /* Saved hook values in case of unload */
457 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
458 static planner_hook_type prev_planner = NULL;
459 static get_relation_info_hook_type prev_get_relation_info = NULL;
460 static join_search_hook_type prev_join_search = NULL;
462 /* Hold reference to currently active hint */
463 static HintState *current_hint = NULL;
466 * List of hint contexts. We treat the head of the list as the Top of the
467 * context stack, so current_hint always points the first element of this list.
469 static List *HintStateStack = NIL;
472 * Holds statement name during executing EXECUTE command. NULL for other
475 static char *stmt_name = NULL;
477 static const HintParser parsers[] = {
478 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
479 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
480 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
481 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
482 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
483 HINT_KEYWORD_BITMAPSCANREGEXP},
484 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
485 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
486 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
487 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
488 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
489 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
490 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
491 HINT_KEYWORD_INDEXONLYSCANREGEXP},
492 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
493 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
494 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
495 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
496 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
497 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
498 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
499 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
500 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
501 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
502 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
506 * PL/pgSQL plugin for retrieving string representation of each query during
507 * function execution.
509 const char *plpgsql_query_string = NULL;
510 PLpgSQL_plugin plugin_funcs = {
514 pg_hint_plan_plpgsql_stmt_beg,
515 pg_hint_plan_plpgsql_stmt_end,
520 /* Current nesting depth of SPI calls, used to prevent recursive calls */
521 static int nested_level = 0;
524 * Module load callbacks
529 PLpgSQL_plugin **var_ptr;
531 /* Define custom GUC variables. */
532 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
533 "Force planner to use plans specified in the hint comment preceding to the query.",
535 &pg_hint_plan_enable_hint,
543 DefineCustomBoolVariable("pg_hint_plan.debug_print",
544 "Logs results of hint parsing.",
546 &pg_hint_plan_debug_print,
554 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
555 "Message level of parse errors.",
557 &pg_hint_plan_parse_messages,
559 parse_messages_level_options,
566 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
567 "Force planner to not get hint by using table lookups.",
569 &pg_hint_plan_enable_hint_table,
578 prev_ProcessUtility = ProcessUtility_hook;
579 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
580 prev_planner = planner_hook;
581 planner_hook = pg_hint_plan_planner;
582 prev_get_relation_info = get_relation_info_hook;
583 get_relation_info_hook = pg_hint_plan_get_relation_info;
584 prev_join_search = join_search_hook;
585 join_search_hook = pg_hint_plan_join_search;
587 /* setup PL/pgSQL plugin hook */
588 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
589 *var_ptr = &plugin_funcs;
593 * Module unload callback
599 PLpgSQL_plugin **var_ptr;
601 /* Uninstall hooks. */
602 ProcessUtility_hook = prev_ProcessUtility;
603 planner_hook = prev_planner;
604 get_relation_info_hook = prev_get_relation_info;
605 join_search_hook = prev_join_search;
607 /* uninstall PL/pgSQL plugin hook */
608 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
613 * create and delete functions the hint object
617 ScanMethodHintCreate(const char *hint_str, const char *keyword,
618 HintKeyword hint_keyword)
620 ScanMethodHint *hint;
622 hint = palloc(sizeof(ScanMethodHint));
623 hint->base.hint_str = hint_str;
624 hint->base.keyword = keyword;
625 hint->base.hint_keyword = hint_keyword;
626 hint->base.type = HINT_TYPE_SCAN_METHOD;
627 hint->base.state = HINT_STATE_NOTUSED;
628 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
629 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
630 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
631 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
632 hint->relname = NULL;
633 hint->indexnames = NIL;
634 hint->regexp = false;
635 hint->enforce_mask = 0;
637 return (Hint *) hint;
641 ScanMethodHintDelete(ScanMethodHint *hint)
647 pfree(hint->relname);
648 list_free_deep(hint->indexnames);
653 JoinMethodHintCreate(const char *hint_str, const char *keyword,
654 HintKeyword hint_keyword)
656 JoinMethodHint *hint;
658 hint = palloc(sizeof(JoinMethodHint));
659 hint->base.hint_str = hint_str;
660 hint->base.keyword = keyword;
661 hint->base.hint_keyword = hint_keyword;
662 hint->base.type = HINT_TYPE_JOIN_METHOD;
663 hint->base.state = HINT_STATE_NOTUSED;
664 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
665 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
666 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
667 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
669 hint->inner_nrels = 0;
670 hint->relnames = NULL;
671 hint->enforce_mask = 0;
672 hint->joinrelids = NULL;
673 hint->inner_joinrelids = NULL;
675 return (Hint *) hint;
679 JoinMethodHintDelete(JoinMethodHint *hint)
688 for (i = 0; i < hint->nrels; i++)
689 pfree(hint->relnames[i]);
690 pfree(hint->relnames);
693 bms_free(hint->joinrelids);
694 bms_free(hint->inner_joinrelids);
699 LeadingHintCreate(const char *hint_str, const char *keyword,
700 HintKeyword hint_keyword)
704 hint = palloc(sizeof(LeadingHint));
705 hint->base.hint_str = hint_str;
706 hint->base.keyword = keyword;
707 hint->base.hint_keyword = hint_keyword;
708 hint->base.type = HINT_TYPE_LEADING;
709 hint->base.state = HINT_STATE_NOTUSED;
710 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
711 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
712 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
713 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
714 hint->relations = NIL;
715 hint->outer_inner = NULL;
717 return (Hint *) hint;
721 LeadingHintDelete(LeadingHint *hint)
726 list_free_deep(hint->relations);
727 if (hint->outer_inner)
728 pfree(hint->outer_inner);
733 SetHintCreate(const char *hint_str, const char *keyword,
734 HintKeyword hint_keyword)
738 hint = palloc(sizeof(SetHint));
739 hint->base.hint_str = hint_str;
740 hint->base.keyword = keyword;
741 hint->base.hint_keyword = hint_keyword;
742 hint->base.type = HINT_TYPE_SET;
743 hint->base.state = HINT_STATE_NOTUSED;
744 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
745 hint->base.desc_func = (HintDescFunction) SetHintDesc;
746 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
747 hint->base.parse_func = (HintParseFunction) SetHintParse;
752 return (Hint *) hint;
756 SetHintDelete(SetHint *hint)
766 list_free(hint->words);
771 RowsHintCreate(const char *hint_str, const char *keyword,
772 HintKeyword hint_keyword)
776 hint = palloc(sizeof(RowsHint));
777 hint->base.hint_str = hint_str;
778 hint->base.keyword = keyword;
779 hint->base.hint_keyword = hint_keyword;
780 hint->base.type = HINT_TYPE_ROWS;
781 hint->base.state = HINT_STATE_NOTUSED;
782 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
783 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
784 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
785 hint->base.parse_func = (HintParseFunction) RowsHintParse;
787 hint->inner_nrels = 0;
788 hint->relnames = NULL;
789 hint->joinrelids = NULL;
790 hint->inner_joinrelids = NULL;
791 hint->rows_str = NULL;
792 hint->value_type = RVT_ABSOLUTE;
795 return (Hint *) hint;
799 RowsHintDelete(RowsHint *hint)
808 for (i = 0; i < hint->nrels; i++)
809 pfree(hint->relnames[i]);
810 pfree(hint->relnames);
813 bms_free(hint->joinrelids);
814 bms_free(hint->inner_joinrelids);
819 HintStateCreate(void)
823 hstate = palloc(sizeof(HintState));
824 hstate->hint_str = NULL;
825 hstate->nall_hints = 0;
826 hstate->max_all_hints = 0;
827 hstate->all_hints = NULL;
828 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
829 hstate->scan_hints = NULL;
830 hstate->init_scan_mask = 0;
831 hstate->parent_relid = 0;
832 hstate->parent_hint = NULL;
833 hstate->parent_index_infos = NIL;
834 hstate->join_hints = NULL;
835 hstate->init_join_mask = 0;
836 hstate->join_hint_level = NULL;
837 hstate->leading_hint = NULL;
838 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
839 hstate->set_hints = NULL;
840 hstate->rows_hints = NULL;
846 HintStateDelete(HintState *hstate)
853 if (hstate->hint_str)
854 pfree(hstate->hint_str);
856 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
857 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
858 if (hstate->all_hints)
859 pfree(hstate->all_hints);
860 if (hstate->parent_index_infos)
861 list_free(hstate->parent_index_infos);
865 * Copy given value into buf, with quoting with '"' if necessary.
868 quote_value(StringInfo buf, const char *value)
870 bool need_quote = false;
873 for (str = value; *str != '\0'; str++)
875 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
878 appendStringInfoCharMacro(buf, '"');
883 for (str = value; *str != '\0'; str++)
886 appendStringInfoCharMacro(buf, '"');
888 appendStringInfoCharMacro(buf, *str);
892 appendStringInfoCharMacro(buf, '"');
896 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
900 appendStringInfo(buf, "%s(", hint->base.keyword);
901 if (hint->relname != NULL)
903 quote_value(buf, hint->relname);
904 foreach(l, hint->indexnames)
906 appendStringInfoCharMacro(buf, ' ');
907 quote_value(buf, (char *) lfirst(l));
910 appendStringInfoString(buf, ")\n");
914 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
918 appendStringInfo(buf, "%s(", hint->base.keyword);
919 if (hint->relnames != NULL)
921 quote_value(buf, hint->relnames[0]);
922 for (i = 1; i < hint->nrels; i++)
924 appendStringInfoCharMacro(buf, ' ');
925 quote_value(buf, hint->relnames[i]);
928 appendStringInfoString(buf, ")\n");
933 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
935 if (outer_inner->relation == NULL)
942 appendStringInfoCharMacro(buf, '(');
943 foreach(l, outer_inner->outer_inner_pair)
948 appendStringInfoCharMacro(buf, ' ');
950 OuterInnerDesc(lfirst(l), buf);
953 appendStringInfoCharMacro(buf, ')');
956 quote_value(buf, outer_inner->relation);
960 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
962 appendStringInfo(buf, "%s(", HINT_LEADING);
963 if (hint->outer_inner == NULL)
970 foreach(l, hint->relations)
975 appendStringInfoCharMacro(buf, ' ');
977 quote_value(buf, (char *) lfirst(l));
981 OuterInnerDesc(hint->outer_inner, buf);
983 appendStringInfoString(buf, ")\n");
987 SetHintDesc(SetHint *hint, StringInfo buf)
989 bool is_first = true;
992 appendStringInfo(buf, "%s(", HINT_SET);
993 foreach(l, hint->words)
998 appendStringInfoCharMacro(buf, ' ');
1000 quote_value(buf, (char *) lfirst(l));
1002 appendStringInfo(buf, ")\n");
1006 RowsHintDesc(RowsHint *hint, StringInfo buf)
1010 appendStringInfo(buf, "%s(", hint->base.keyword);
1011 if (hint->relnames != NULL)
1013 quote_value(buf, hint->relnames[0]);
1014 for (i = 1; i < hint->nrels; i++)
1016 appendStringInfoCharMacro(buf, ' ');
1017 quote_value(buf, hint->relnames[i]);
1020 appendStringInfo(buf, " %s", hint->rows_str);
1021 appendStringInfoString(buf, ")\n");
1026 * Append string which represents all hints in a given state to buf, with
1027 * preceding title with them.
1030 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1035 appendStringInfo(buf, "%s:\n", title);
1036 for (i = 0; i < hstate->nall_hints; i++)
1038 if (hstate->all_hints[i]->state != state)
1041 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
1046 * Dump contents of given hstate to server log with log level LOG.
1049 HintStateDump(HintState *hstate)
1055 elog(LOG, "pg_hint_plan:\nno hint");
1059 initStringInfo(&buf);
1061 appendStringInfoString(&buf, "pg_hint_plan:\n");
1062 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
1063 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
1064 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
1065 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
1067 elog(LOG, "%s", buf.data);
1077 RelnameCmp(const void *a, const void *b)
1079 const char *relnamea = *((const char **) a);
1080 const char *relnameb = *((const char **) b);
1082 return strcmp(relnamea, relnameb);
1086 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1088 return RelnameCmp(&a->relname, &b->relname);
1092 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1096 if (a->nrels != b->nrels)
1097 return a->nrels - b->nrels;
1099 for (i = 0; i < a->nrels; i++)
1102 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1110 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1116 SetHintCmp(const SetHint *a, const SetHint *b)
1118 return strcmp(a->name, b->name);
1122 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1126 if (a->nrels != b->nrels)
1127 return a->nrels - b->nrels;
1129 for (i = 0; i < a->nrels; i++)
1132 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1140 HintCmp(const void *a, const void *b)
1142 const Hint *hinta = *((const Hint **) a);
1143 const Hint *hintb = *((const Hint **) b);
1145 if (hinta->type != hintb->type)
1146 return hinta->type - hintb->type;
1147 if (hinta->state == HINT_STATE_ERROR)
1149 if (hintb->state == HINT_STATE_ERROR)
1151 return hinta->cmp_func(hinta, hintb);
1155 * Returns byte offset of hint b from hint a. If hint a was specified before
1156 * b, positive value is returned.
1159 HintCmpWithPos(const void *a, const void *b)
1161 const Hint *hinta = *((const Hint **) a);
1162 const Hint *hintb = *((const Hint **) b);
1165 result = HintCmp(a, b);
1167 result = hinta->hint_str - hintb->hint_str;
1176 parse_keyword(const char *str, StringInfo buf)
1180 while (!isspace(*str) && *str != '(' && *str != '\0')
1181 appendStringInfoCharMacro(buf, *str++);
1187 skip_parenthesis(const char *str, char parenthesis)
1191 if (*str != parenthesis)
1193 if (parenthesis == '(')
1194 hint_ereport(str, ("Opening parenthesis is necessary."));
1195 else if (parenthesis == ')')
1196 hint_ereport(str, ("Closing parenthesis is necessary."));
1207 * Parse a token from str, and store malloc'd copy into word. A token can be
1208 * quoted with '"'. Return value is pointer to unparsed portion of original
1209 * string, or NULL if an error occurred.
1211 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1214 parse_quoted_value(const char *str, char **word, bool truncate)
1219 /* Skip leading spaces. */
1222 initStringInfo(&buf);
1235 /* Double quotation must be closed. */
1239 hint_ereport(str, ("Unterminated quoted string."));
1244 * Skip escaped double quotation.
1246 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1247 * block comments) to be an object name, so users must specify
1248 * alias for such object names.
1250 * Those special names can be allowed if we care escaped slashes
1251 * and asterisks, but we don't.
1260 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1264 appendStringInfoCharMacro(&buf, *str++);
1269 hint_ereport(str, ("Zero-length delimited string."));
1276 /* Truncate name if it's too long */
1278 truncate_identifier(buf.data, strlen(buf.data), true);
1285 static OuterInnerRels *
1286 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1288 OuterInnerRels *outer_inner;
1290 outer_inner = palloc(sizeof(OuterInnerRels));
1291 outer_inner->relation = name;
1292 outer_inner->outer_inner_pair = outer_inner_list;
1298 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1300 List *outer_inner_pair = NIL;
1302 if ((str = skip_parenthesis(str, '(')) == NULL)
1307 /* Store words in parentheses into outer_inner_list. */
1308 while(*str != ')' && *str != '\0')
1310 OuterInnerRels *outer_inner_rels;
1314 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1322 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1325 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1328 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1333 (str = skip_parenthesis(str, ')')) == NULL)
1335 list_free(outer_inner_pair);
1339 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1345 parse_parentheses_Leading(const char *str, List **name_list,
1346 OuterInnerRels **outer_inner)
1349 bool truncate = true;
1351 if ((str = skip_parenthesis(str, '(')) == NULL)
1357 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1362 /* Store words in parentheses into name_list. */
1363 while(*str != ')' && *str != '\0')
1365 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1367 list_free(*name_list);
1371 *name_list = lappend(*name_list, name);
1376 if ((str = skip_parenthesis(str, ')')) == NULL)
1382 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1385 bool truncate = true;
1387 if ((str = skip_parenthesis(str, '(')) == NULL)
1392 /* Store words in parentheses into name_list. */
1393 while(*str != ')' && *str != '\0')
1395 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1397 list_free(*name_list);
1401 *name_list = lappend(*name_list, name);
1404 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1405 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1406 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1407 keyword == HINT_KEYWORD_SET)
1413 if ((str = skip_parenthesis(str, ')')) == NULL)
1419 parse_hints(HintState *hstate, Query *parse, const char *str)
1424 initStringInfo(&buf);
1425 while (*str != '\0')
1427 const HintParser *parser;
1429 /* in error message, we output the comment including the keyword. */
1430 head = (char *) str;
1432 /* parse only the keyword of the hint. */
1433 resetStringInfo(&buf);
1434 str = parse_keyword(str, &buf);
1436 for (parser = parsers; parser->keyword != NULL; parser++)
1438 char *keyword = parser->keyword;
1441 if (strcasecmp(buf.data, keyword) != 0)
1444 hint = parser->create_func(head, keyword, parser->hint_keyword);
1446 /* parser of each hint does parse in a parenthesis. */
1447 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1449 hint->delete_func(hint);
1455 * Add hint information into all_hints array. If we don't have
1456 * enough space, double the array.
1458 if (hstate->nall_hints == 0)
1460 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1461 hstate->all_hints = (Hint **)
1462 palloc(sizeof(Hint *) * hstate->max_all_hints);
1464 else if (hstate->nall_hints == hstate->max_all_hints)
1466 hstate->max_all_hints *= 2;
1467 hstate->all_hints = (Hint **)
1468 repalloc(hstate->all_hints,
1469 sizeof(Hint *) * hstate->max_all_hints);
1472 hstate->all_hints[hstate->nall_hints] = hint;
1473 hstate->nall_hints++;
1480 if (parser->keyword == NULL)
1483 ("Unrecognized hint keyword \"%s\".", buf.data));
1494 * Get hints from table by client-supplied query string and application name.
1497 get_hints_from_table(const char *client_query, const char *client_application)
1499 const char *search_query =
1501 " FROM hint_plan.hints "
1502 " WHERE norm_query_string = $1 "
1503 " AND ( application_name = $2 "
1504 " OR application_name = '' ) "
1505 " ORDER BY application_name DESC";
1506 static SPIPlanPtr plan = NULL;
1508 Oid argtypes[2] = { TEXTOID, TEXTOID };
1510 bool nulls[2] = { false, false };
1523 p = SPI_prepare(search_query, 2, argtypes);
1524 plan = SPI_saveplan(p);
1528 qry = cstring_to_text(client_query);
1529 app = cstring_to_text(client_application);
1530 values[0] = PointerGetDatum(qry);
1531 values[1] = PointerGetDatum(app);
1533 SPI_execute_plan(plan, values, nulls, true, 1);
1535 if (SPI_processed > 0)
1539 hints = SPI_getvalue(SPI_tuptable->vals[0],
1540 SPI_tuptable->tupdesc, 1);
1542 * Here we use SPI_palloc to ensure that hints string is valid even
1543 * after SPI_finish call. We can't use simple palloc because it
1544 * allocates memory in SPI's context and that context is deleted in
1547 buf = SPI_palloc(strlen(hints) + 1);
1567 * Get client-supplied query string.
1570 get_query_string(void)
1576 PreparedStatement *entry;
1578 entry = FetchPreparedStatement(stmt_name, true);
1579 p = entry->plansource->query_string;
1581 else if (plpgsql_query_string)
1582 p = plpgsql_query_string;
1584 p = debug_query_string;
1590 * Get hints from the head block comment in client-supplied query string.
1593 get_hints_from_comment(const char *p)
1595 const char *hint_head;
1603 /* extract query head comment. */
1604 hint_head = strstr(p, HINT_START);
1605 if (hint_head == NULL)
1607 for (;p < hint_head; p++)
1610 * Allow these characters precedes hint comment:
1612 * - alphabets which are in ASCII range
1613 * - space, tabs and new-lines
1614 * - underscores, for identifier
1615 * - commas, for SELECT clause, EXPLAIN and PREPARE
1616 * - parentheses, for EXPLAIN and PREPARE
1618 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1619 * avoid behavior which depends on locale setting.
1621 if (!(*p >= '0' && *p <= '9') &&
1622 !(*p >= 'A' && *p <= 'Z') &&
1623 !(*p >= 'a' && *p <= 'z') &&
1627 *p != '(' && *p != ')')
1631 len = strlen(HINT_START);
1636 /* find hint end keyword. */
1637 if ((tail = strstr(p, HINT_END)) == NULL)
1639 hint_ereport(head, ("Unterminated block comment."));
1643 /* We don't support nested block comments. */
1644 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1646 hint_ereport(head, ("Nested block comments are not supported."));
1650 /* Make a copy of hint. */
1652 head = palloc(len + 1);
1653 memcpy(head, p, len);
1661 * Parse hints that got, create hint struct from parse tree and parse hints.
1664 create_hintstate(Query *parse, const char *hints)
1674 hstate = HintStateCreate();
1675 hstate->hint_str = (char *) hints;
1677 /* parse each hint. */
1678 parse_hints(hstate, parse, p);
1680 /* When nothing specified a hint, we free HintState and returns NULL. */
1681 if (hstate->nall_hints == 0)
1683 HintStateDelete(hstate);
1687 /* Sort hints in order of original position. */
1688 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1691 /* Count number of hints per hint-type. */
1692 for (i = 0; i < hstate->nall_hints; i++)
1694 Hint *cur_hint = hstate->all_hints[i];
1695 hstate->num_hints[cur_hint->type]++;
1699 * If an object (or a set of objects) has multiple hints of same hint-type,
1700 * only the last hint is valid and others are ignored in planning.
1701 * Hints except the last are marked as 'duplicated' to remember the order.
1703 for (i = 0; i < hstate->nall_hints - 1; i++)
1705 Hint *cur_hint = hstate->all_hints[i];
1706 Hint *next_hint = hstate->all_hints[i + 1];
1709 * Leading hint is marked as 'duplicated' in transform_join_hints.
1711 if (cur_hint->type == HINT_TYPE_LEADING &&
1712 next_hint->type == HINT_TYPE_LEADING)
1716 * Note that we need to pass addresses of hint pointers, because
1717 * HintCmp is designed to sort array of Hint* by qsort.
1719 if (HintCmp(&cur_hint, &next_hint) == 0)
1721 hint_ereport(cur_hint->hint_str,
1722 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1723 cur_hint->state = HINT_STATE_DUPLICATION;
1728 * Make sure that per-type array pointers point proper position in the
1729 * array which consists of all hints.
1731 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1732 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1733 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1734 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1735 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1736 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1737 hstate->num_hints[HINT_TYPE_LEADING]);
1738 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1739 hstate->num_hints[HINT_TYPE_SET]);
1745 * Parse inside of parentheses of scan-method hints.
1748 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1751 const char *keyword = hint->base.keyword;
1752 HintKeyword hint_keyword = hint->base.hint_keyword;
1753 List *name_list = NIL;
1756 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1759 /* Parse relation name and index name(s) if given hint accepts. */
1760 length = list_length(name_list);
1763 hint->relname = linitial(name_list);
1764 hint->indexnames = list_delete_first(name_list);
1766 /* check whether the hint accepts index name(s). */
1768 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1769 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1770 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1771 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1772 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1773 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1776 ("%s hint accepts only one relation.",
1777 hint->base.keyword));
1778 hint->base.state = HINT_STATE_ERROR;
1785 ("%s hint requires a relation.",
1786 hint->base.keyword));
1787 hint->base.state = HINT_STATE_ERROR;
1791 /* Set a bit for specified hint. */
1792 switch (hint_keyword)
1794 case HINT_KEYWORD_SEQSCAN:
1795 hint->enforce_mask = ENABLE_SEQSCAN;
1797 case HINT_KEYWORD_INDEXSCAN:
1798 hint->enforce_mask = ENABLE_INDEXSCAN;
1800 case HINT_KEYWORD_INDEXSCANREGEXP:
1801 hint->enforce_mask = ENABLE_INDEXSCAN;
1802 hint->regexp = true;
1804 case HINT_KEYWORD_BITMAPSCAN:
1805 hint->enforce_mask = ENABLE_BITMAPSCAN;
1807 case HINT_KEYWORD_BITMAPSCANREGEXP:
1808 hint->enforce_mask = ENABLE_BITMAPSCAN;
1809 hint->regexp = true;
1811 case HINT_KEYWORD_TIDSCAN:
1812 hint->enforce_mask = ENABLE_TIDSCAN;
1814 case HINT_KEYWORD_NOSEQSCAN:
1815 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1817 case HINT_KEYWORD_NOINDEXSCAN:
1818 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1820 case HINT_KEYWORD_NOBITMAPSCAN:
1821 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1823 case HINT_KEYWORD_NOTIDSCAN:
1824 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1826 case HINT_KEYWORD_INDEXONLYSCAN:
1827 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1829 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1830 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1831 hint->regexp = true;
1833 case HINT_KEYWORD_NOINDEXONLYSCAN:
1834 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1837 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1846 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1849 const char *keyword = hint->base.keyword;
1850 HintKeyword hint_keyword = hint->base.hint_keyword;
1851 List *name_list = NIL;
1853 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1856 hint->nrels = list_length(name_list);
1858 if (hint->nrels > 0)
1864 * Transform relation names from list to array to sort them with qsort
1867 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1868 foreach (l, name_list)
1870 hint->relnames[i] = lfirst(l);
1875 list_free(name_list);
1877 /* A join hint requires at least two relations */
1878 if (hint->nrels < 2)
1881 ("%s hint requires at least two relations.",
1882 hint->base.keyword));
1883 hint->base.state = HINT_STATE_ERROR;
1887 /* Sort hints in alphabetical order of relation names. */
1888 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1890 switch (hint_keyword)
1892 case HINT_KEYWORD_NESTLOOP:
1893 hint->enforce_mask = ENABLE_NESTLOOP;
1895 case HINT_KEYWORD_MERGEJOIN:
1896 hint->enforce_mask = ENABLE_MERGEJOIN;
1898 case HINT_KEYWORD_HASHJOIN:
1899 hint->enforce_mask = ENABLE_HASHJOIN;
1901 case HINT_KEYWORD_NONESTLOOP:
1902 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1904 case HINT_KEYWORD_NOMERGEJOIN:
1905 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1907 case HINT_KEYWORD_NOHASHJOIN:
1908 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1911 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1920 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1923 if (outer_inner->outer_inner_pair == NIL)
1925 if (outer_inner->relation)
1931 if (list_length(outer_inner->outer_inner_pair) == 2)
1933 foreach(l, outer_inner->outer_inner_pair)
1935 if (!OuterInnerPairCheck(lfirst(l)))
1946 OuterInnerList(OuterInnerRels *outer_inner)
1948 List *outer_inner_list = NIL;
1950 OuterInnerRels *outer_inner_rels;
1952 foreach(l, outer_inner->outer_inner_pair)
1954 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1956 if (outer_inner_rels->relation != NULL)
1957 outer_inner_list = lappend(outer_inner_list,
1958 outer_inner_rels->relation);
1960 outer_inner_list = list_concat(outer_inner_list,
1961 OuterInnerList(outer_inner_rels));
1963 return outer_inner_list;
1967 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1970 List *name_list = NIL;
1971 OuterInnerRels *outer_inner = NULL;
1973 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1977 if (outer_inner != NULL)
1978 name_list = OuterInnerList(outer_inner);
1980 hint->relations = name_list;
1981 hint->outer_inner = outer_inner;
1983 /* A Leading hint requires at least two relations */
1984 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1986 hint_ereport(hint->base.hint_str,
1987 ("%s hint requires at least two relations.",
1989 hint->base.state = HINT_STATE_ERROR;
1991 else if (hint->outer_inner != NULL &&
1992 !OuterInnerPairCheck(hint->outer_inner))
1994 hint_ereport(hint->base.hint_str,
1995 ("%s hint requires two sets of relations when parentheses nests.",
1997 hint->base.state = HINT_STATE_ERROR;
2004 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2006 List *name_list = NIL;
2008 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2012 hint->words = name_list;
2014 /* We need both name and value to set GUC parameter. */
2015 if (list_length(name_list) == 2)
2017 hint->name = linitial(name_list);
2018 hint->value = lsecond(name_list);
2022 hint_ereport(hint->base.hint_str,
2023 ("%s hint requires name and value of GUC parameter.",
2025 hint->base.state = HINT_STATE_ERROR;
2032 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2035 HintKeyword hint_keyword = hint->base.hint_keyword;
2036 List *name_list = NIL;
2040 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2043 /* Last element must be rows specification */
2044 hint->nrels = list_length(name_list) - 1;
2046 if (hint->nrels > 0)
2052 * Transform relation names from list to array to sort them with qsort
2055 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2056 foreach (l, name_list)
2058 if (hint->nrels <= i)
2060 hint->relnames[i] = lfirst(l);
2065 /* Retieve rows estimation */
2066 rows_str = list_nth(name_list, hint->nrels);
2067 hint->rows_str = rows_str; /* store as-is for error logging */
2068 if (rows_str[0] == '#')
2070 hint->value_type = RVT_ABSOLUTE;
2073 else if (rows_str[0] == '+')
2075 hint->value_type = RVT_ADD;
2078 else if (rows_str[0] == '-')
2080 hint->value_type = RVT_SUB;
2083 else if (rows_str[0] == '*')
2085 hint->value_type = RVT_MULTI;
2090 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2091 hint->base.state = HINT_STATE_ERROR;
2094 hint->rows = strtod(rows_str, &end_ptr);
2097 hint_ereport(rows_str,
2098 ("%s hint requires valid number as rows estimation.",
2099 hint->base.keyword));
2100 hint->base.state = HINT_STATE_ERROR;
2104 /* A join hint requires at least two relations */
2105 if (hint->nrels < 2)
2108 ("%s hint requires at least two relations.",
2109 hint->base.keyword));
2110 hint->base.state = HINT_STATE_ERROR;
2114 list_free(name_list);
2116 /* Sort relnames in alphabetical order. */
2117 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2123 * set GUC parameter functions
2127 set_config_option_wrapper(const char *name, const char *value,
2128 GucContext context, GucSource source,
2129 GucAction action, bool changeVal, int elevel)
2132 MemoryContext ccxt = CurrentMemoryContext;
2136 result = set_config_option(name, value, context, source,
2137 action, changeVal, 0);
2143 /* Save error info */
2144 MemoryContextSwitchTo(ccxt);
2145 errdata = CopyErrorData();
2148 ereport(elevel, (errcode(errdata->sqlerrcode),
2149 errmsg("%s", errdata->message),
2150 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2151 errdata->hint ? errhint("%s", errdata->hint) : 0));
2152 FreeErrorData(errdata);
2160 set_config_options(SetHint **options, int noptions, GucContext context)
2165 save_nestlevel = NewGUCNestLevel();
2167 for (i = 0; i < noptions; i++)
2169 SetHint *hint = options[i];
2172 if (!hint_state_enabled(hint))
2175 result = set_config_option_wrapper(hint->name, hint->value, context,
2176 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2177 pg_hint_plan_parse_messages);
2179 hint->base.state = HINT_STATE_USED;
2181 hint->base.state = HINT_STATE_ERROR;
2184 return save_nestlevel;
2187 #define SET_CONFIG_OPTION(name, type_bits) \
2188 set_config_option_wrapper((name), \
2189 (mask & (type_bits)) ? "true" : "false", \
2190 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2193 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2197 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2198 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2199 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2201 mask = enforce_mask;
2203 mask = enforce_mask & current_hint->init_scan_mask;
2205 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2206 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2207 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2208 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2209 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2213 set_join_config_options(unsigned char enforce_mask, GucContext context)
2217 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2218 enforce_mask == ENABLE_HASHJOIN)
2219 mask = enforce_mask;
2221 mask = enforce_mask & current_hint->init_join_mask;
2223 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2224 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2225 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2229 * pg_hint_plan hook functions
2233 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2234 ProcessUtilityContext context,
2235 ParamListInfo params,
2236 DestReceiver *dest, char *completionTag)
2241 * Use standard planner if pg_hint_plan is disabled or current nesting
2242 * depth is nesting depth of SPI calls.
2244 if (!pg_hint_plan_enable_hint || nested_level > 0)
2246 if (prev_ProcessUtility)
2247 (*prev_ProcessUtility) (parsetree, queryString,
2249 dest, completionTag);
2251 standard_ProcessUtility(parsetree, queryString,
2253 dest, completionTag);
2258 if (IsA(node, ExplainStmt))
2261 * Draw out parse tree of actual query from Query struct of EXPLAIN
2267 stmt = (ExplainStmt *) node;
2269 Assert(IsA(stmt->query, Query));
2270 query = (Query *) stmt->query;
2272 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2273 node = query->utilityStmt;
2277 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2278 * specified to preceding PREPARE command to use it as source of hints.
2280 if (IsA(node, ExecuteStmt))
2284 stmt = (ExecuteStmt *) node;
2285 stmt_name = stmt->name;
2289 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2292 if (IsA(node, CreateTableAsStmt))
2294 CreateTableAsStmt *stmt;
2297 stmt = (CreateTableAsStmt *) node;
2298 Assert(IsA(stmt->query, Query));
2299 query = (Query *) stmt->query;
2301 if (query->commandType == CMD_UTILITY &&
2302 IsA(query->utilityStmt, ExecuteStmt))
2304 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2305 stmt_name = estmt->name;
2313 if (prev_ProcessUtility)
2314 (*prev_ProcessUtility) (parsetree, queryString,
2316 dest, completionTag);
2318 standard_ProcessUtility(parsetree, queryString,
2320 dest, completionTag);
2334 if (prev_ProcessUtility)
2335 (*prev_ProcessUtility) (parsetree, queryString,
2337 dest, completionTag);
2339 standard_ProcessUtility(parsetree, queryString,
2341 dest, completionTag);
2345 * Push a hint into hint stack which is implemented with List struct. Head of
2346 * list is top of stack.
2349 push_hint(HintState *hstate)
2351 /* Prepend new hint to the list means pushing to stack. */
2352 HintStateStack = lcons(hstate, HintStateStack);
2354 /* Pushed hint is the one which should be used hereafter. */
2355 current_hint = hstate;
2358 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2362 /* Hint stack must not be empty. */
2363 if(HintStateStack == NIL)
2364 elog(ERROR, "hint stack is empty");
2367 * Take a hint at the head from the list, and free it. Switch current_hint
2368 * to point new head (NULL if the list is empty).
2370 HintStateStack = list_delete_first(HintStateStack);
2371 HintStateDelete(current_hint);
2372 if(HintStateStack == NIL)
2373 current_hint = NULL;
2375 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2378 static PlannedStmt *
2379 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2381 const char *hints = NULL;
2384 pgssJumbleState jstate;
2387 PlannedStmt *result;
2391 * Use standard planner if pg_hint_plan is disabled or current nesting
2392 * depth is nesting depth of SPI calls. Other hook functions try to change
2393 * plan with current_hint if any, so set it to NULL.
2395 if (!pg_hint_plan_enable_hint || nested_level > 0)
2396 goto standard_planner_proc;
2398 /* Create hint struct from client-supplied query string. */
2399 query = get_query_string();
2402 * Create hintstate from hint specified for the query, if any.
2404 * First we lookup hint in pg_hint.hints table by normalized query string,
2405 * unless pg_hint_plan.enable_hint_table is OFF.
2406 * This parameter provides option to avoid overhead of table lookup during
2409 * If no hint was found, then we try to get hint from special query comment.
2411 if (pg_hint_plan_enable_hint_table)
2414 * Search hint information which is stored for the query and the
2415 * application. Query string is normalized before using in condition
2416 * in order to allow fuzzy matching.
2418 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2419 * careful when supporting PostgreSQL's version up.
2421 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2422 jstate.jumble_len = 0;
2423 jstate.clocations_buf_size = 32;
2424 jstate.clocations = (pgssLocationLen *)
2425 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2426 jstate.clocations_count = 0;
2427 JumbleQuery(&jstate, parse);
2429 * generate_normalized_query() copies exact given query_len bytes, so we
2430 * add 1 byte for null-termination here. As comments on
2431 * generate_normalized_query says, generate_normalized_query doesn't
2432 * take care of null-terminate, but additional 1 byte ensures that '\0'
2433 * byte in the source buffer to be copied into norm_query.
2435 query_len = strlen(query) + 1;
2436 norm_query = generate_normalized_query(&jstate,
2439 GetDatabaseEncoding());
2440 hints = get_hints_from_table(norm_query, application_name);
2442 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2443 norm_query, application_name, hints ? hints : "(none)");
2446 hints = get_hints_from_comment(query);
2447 hstate = create_hintstate(parse, hints);
2450 * Use standard planner if the statement has not valid hint. Other hook
2451 * functions try to change plan with current_hint if any, so set it to
2455 goto standard_planner_proc;
2458 * Push new hint struct to the hint stack to disable previous hint context.
2462 /* Set GUC parameters which are specified with Set hint. */
2463 save_nestlevel = set_config_options(current_hint->set_hints,
2464 current_hint->num_hints[HINT_TYPE_SET],
2465 current_hint->context);
2468 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2469 if (enable_indexscan)
2470 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2471 if (enable_bitmapscan)
2472 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2474 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2475 if (enable_indexonlyscan)
2476 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2477 if (enable_nestloop)
2478 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2479 if (enable_mergejoin)
2480 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2481 if (enable_hashjoin)
2482 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2485 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2486 * state when this planner started when error occurred in planner.
2491 result = (*prev_planner) (parse, cursorOptions, boundParams);
2493 result = standard_planner(parse, cursorOptions, boundParams);
2498 * Rollback changes of GUC parameters, and pop current hint context
2499 * from hint stack to rewind the state.
2501 AtEOXact_GUC(true, save_nestlevel);
2507 /* Print hint in debug mode. */
2508 if (pg_hint_plan_debug_print)
2509 HintStateDump(current_hint);
2512 * Rollback changes of GUC parameters, and pop current hint context from
2513 * hint stack to rewind the state.
2515 AtEOXact_GUC(true, save_nestlevel);
2520 standard_planner_proc:
2521 current_hint = NULL;
2523 return (*prev_planner) (parse, cursorOptions, boundParams);
2525 return standard_planner(parse, cursorOptions, boundParams);
2529 * Return scan method hint which matches given aliasname.
2531 static ScanMethodHint *
2532 find_scan_hint(PlannerInfo *root, Index relid, RelOptInfo *rel)
2538 * We can't apply scan method hint if the relation is:
2539 * - not a base relation
2540 * - not an ordinary relation (such as join and subquery)
2542 if (rel && (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION))
2545 rte = root->simple_rte_array[relid];
2547 /* We can't force scan method of foreign tables */
2548 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2551 /* Find scan method hint, which matches given names, from the list. */
2552 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2554 ScanMethodHint *hint = current_hint->scan_hints[i];
2556 /* We ignore disabled hints. */
2557 if (!hint_state_enabled(hint))
2560 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2570 * Returns TRUE on match, FALSE on no match.
2572 * s1 --- the data to match against
2573 * s2 --- the pattern
2575 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2578 regexpeq(const char *s1, const char *s2)
2584 strcpy(name.data, s1);
2585 regexp = cstring_to_text(s2);
2587 result = DirectFunctionCall2Coll(nameregexeq,
2588 DEFAULT_COLLATION_OID,
2589 NameGetDatum(&name),
2590 PointerGetDatum(regexp));
2591 return DatumGetBool(result);
2595 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2603 * We delete all the IndexOptInfo list and prevent you from being usable by
2606 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2607 hint->enforce_mask == ENABLE_TIDSCAN)
2609 list_free_deep(rel->indexlist);
2610 rel->indexlist = NIL;
2611 hint->base.state = HINT_STATE_USED;
2617 * When a list of indexes is not specified, we just use all indexes.
2619 if (hint->indexnames == NIL)
2623 * Leaving only an specified index, we delete it from a IndexOptInfo list
2627 if (pg_hint_plan_debug_print)
2628 initStringInfo(&buf);
2630 for (cell = list_head(rel->indexlist); cell; cell = next)
2632 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2633 char *indexname = get_rel_name(info->indexoid);
2635 bool use_index = false;
2639 foreach(l, hint->indexnames)
2641 char *hintname = (char *) lfirst(l);
2645 result = regexpeq(indexname, hintname);
2647 result = RelnameCmp(&indexname, &hintname) == 0;
2652 if (pg_hint_plan_debug_print)
2654 appendStringInfoCharMacro(&buf, ' ');
2655 quote_value(&buf, indexname);
2663 * to make the index a candidate when definition of this index is
2664 * matched with the index's definition of current_hint.
2666 if (OidIsValid(relationObjectId) && !use_index)
2668 foreach(l, current_hint->parent_index_infos)
2672 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2674 /* check to match the parameter of unique */
2675 if (p_info->indisunique != info->unique)
2678 /* check to match the parameter of index's method */
2679 if (p_info->method != info->relam)
2682 /* to check to match the indexkey's configuration */
2683 if ((list_length(p_info->column_names)) !=
2687 /* check to match the indexkey's configuration */
2688 for (i = 0; i < info->ncolumns; i++)
2690 char *c_attname = NULL;
2691 char *p_attname = NULL;
2694 list_nth(p_info->column_names, i);
2696 /* both are expressions */
2697 if (info->indexkeys[i] == 0 && !p_attname)
2700 /* one's column is expression, the other is not */
2701 if (info->indexkeys[i] == 0 || !p_attname)
2704 c_attname = get_attname(relationObjectId,
2705 info->indexkeys[i]);
2707 if (strcmp(p_attname, c_attname) != 0)
2710 if (p_info->indcollation[i] != info->indexcollations[i])
2713 if (p_info->opclass[i] != info->opcintype[i])
2716 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2717 info->reverse_sort[i])
2720 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2721 info->nulls_first[i])
2726 if (i != info->ncolumns)
2729 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2730 (p_info->indpred_str && (info->indpred != NIL)))
2733 * Fetch the pg_index tuple by the Oid of the index
2735 ht_idx = SearchSysCache1(INDEXRELID,
2736 ObjectIdGetDatum(info->indexoid));
2738 /* check to match the expression's parameter of index */
2739 if (p_info->expression_str &&
2740 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2747 * to change the expression's parameter of child's
2750 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2751 Anum_pg_index_indexprs,
2754 result = DirectFunctionCall2(pg_get_expr,
2759 if (strcmp(p_info->expression_str,
2760 text_to_cstring(DatumGetTextP(result))) != 0)
2763 ReleaseSysCache(ht_idx);
2769 /* Check to match the predicate's parameter of index */
2770 if (p_info->indpred_str &&
2771 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2778 * to change the predicate's parameter of child's
2781 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2782 Anum_pg_index_indpred,
2785 result = DirectFunctionCall2(pg_get_expr,
2790 if (strcmp(p_info->indpred_str,
2791 text_to_cstring(DatumGetTextP(result))) != 0)
2794 ReleaseSysCache(ht_idx);
2801 ReleaseSysCache(ht_idx);
2803 else if (p_info->expression_str || (info->indexprs != NIL))
2805 else if (p_info->indpred_str || (info->indpred != NIL))
2810 /* to log the candidate of index */
2811 if (pg_hint_plan_debug_print)
2813 appendStringInfoCharMacro(&buf, ' ');
2814 quote_value(&buf, indexname);
2822 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2829 if (pg_hint_plan_debug_print)
2832 StringInfoData rel_buf;
2834 if (OidIsValid(relationObjectId))
2835 relname = get_rel_name(relationObjectId);
2837 relname = hint->relname;
2839 initStringInfo(&rel_buf);
2840 quote_value(&rel_buf, relname);
2843 (errmsg("available indexes for %s(%s):%s",
2848 pfree(rel_buf.data);
2853 * Return information of index definition.
2855 static ParentIndexInfo *
2856 get_parent_index_info(Oid indexoid, Oid relid)
2858 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2859 Relation indexRelation;
2860 Form_pg_index index;
2864 indexRelation = index_open(indexoid, RowExclusiveLock);
2866 index = indexRelation->rd_index;
2868 p_info->indisunique = index->indisunique;
2869 p_info->method = indexRelation->rd_rel->relam;
2871 p_info->column_names = NIL;
2872 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2873 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2874 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2876 for (i = 0; i < index->indnatts; i++)
2878 attname = get_attname(relid, index->indkey.values[i]);
2879 p_info->column_names = lappend(p_info->column_names, attname);
2881 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2882 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2883 p_info->indoption[i] = indexRelation->rd_indoption[i];
2887 * to check to match the expression's parameter of index with child indexes
2889 p_info->expression_str = NULL;
2890 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2896 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2897 Anum_pg_index_indexprs, &isnull);
2899 result = DirectFunctionCall2(pg_get_expr,
2901 ObjectIdGetDatum(relid));
2903 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2907 * to check to match the predicate's parameter of index with child indexes
2909 p_info->indpred_str = NULL;
2910 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2916 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2917 Anum_pg_index_indpred, &isnull);
2919 result = DirectFunctionCall2(pg_get_expr,
2921 ObjectIdGetDatum(relid));
2923 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2926 index_close(indexRelation, NoLock);
2932 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2933 bool inhparent, RelOptInfo *rel)
2935 ScanMethodHint *hint = NULL;
2937 Index new_parent_relid = 0;
2939 if (prev_get_relation_info)
2940 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2943 * Do nothing if we don't have a valid hint in this context or current
2944 * nesting depth is at SPI calls.
2946 if (!current_hint || nested_level > 0)
2950 * We could register the parent relation of the following children here
2951 * when inhparent == true but inheritnce planner doesn't request
2952 * information for inheritance parents. We also cannot distinguish the
2953 * caller so we should always find the parents without this function being
2959 /* Find the parent for this relation */
2960 foreach (l, root->append_rel_list)
2962 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2964 if (appinfo->child_relid == rel->relid)
2966 if (current_hint->parent_relid != appinfo->parent_relid)
2967 new_parent_relid = appinfo->parent_relid;
2974 /* This relation doesn't have a parent. Cancel current_hint. */
2975 current_hint->parent_relid = 0;
2976 current_hint->parent_hint = NULL;
2979 if (new_parent_relid > 0)
2982 * Here we found a parent relation different from the remembered one.
2983 * Remember it, apply the scan mask of it and then resolve the index
2984 * restriction in order to be used by its children.
2986 int scanmask = current_hint->init_scan_mask;
2987 ScanMethodHint *parent_hint;
2989 current_hint->parent_relid = new_parent_relid;
2992 * Get and apply the hint for the new parent relation. It should be an
2993 * ordinary relation so calling find_scan_hint with rel == NULL is
2996 current_hint->parent_hint = parent_hint =
2997 find_scan_hint(root, current_hint->parent_relid, NULL);
3001 scanmask = current_hint->parent_hint->enforce_mask;
3002 parent_hint->base.state = HINT_STATE_USED;
3004 /* Resolve index name mask (if any) using the parent. */
3005 if (parent_hint->indexnames)
3008 Relation parent_rel;
3011 root->simple_rte_array[current_hint->parent_relid]->relid;
3012 parent_rel = heap_open(parentrel_oid, NoLock);
3014 /* Search the parent relation for indexes match the hint spec */
3015 foreach(l, RelationGetIndexList(parent_rel))
3017 Oid indexoid = lfirst_oid(l);
3018 char *indexname = get_rel_name(indexoid);
3020 ParentIndexInfo *parent_index_info;
3022 foreach(lc, parent_hint->indexnames)
3024 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3031 get_parent_index_info(indexoid, parentrel_oid);
3032 current_hint->parent_index_infos =
3033 lappend(current_hint->parent_index_infos, parent_index_info);
3035 heap_close(parent_rel, NoLock);
3039 set_scan_config_options(scanmask, current_hint->context);
3042 if (current_hint->parent_hint != 0)
3044 delete_indexes(current_hint->parent_hint, rel,
3047 /* Scan fixation status is the same to the parent. */
3051 /* This table doesn't have a parent hint. Apply its own hint if any. */
3052 if ((hint = find_scan_hint(root, rel->relid, rel)) != NULL)
3054 set_scan_config_options(hint->enforce_mask, current_hint->context);
3055 hint->base.state = HINT_STATE_USED;
3057 delete_indexes(hint, rel, InvalidOid);
3060 set_scan_config_options(current_hint->init_scan_mask,
3061 current_hint->context);
3066 * Return index of relation which matches given aliasname, or 0 if not found.
3067 * If same aliasname was used multiple times in a query, return -1.
3070 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3076 for (i = 1; i < root->simple_rel_array_size; i++)
3080 if (root->simple_rel_array[i] == NULL)
3083 Assert(i == root->simple_rel_array[i]->relid);
3085 if (RelnameCmp(&aliasname,
3086 &root->simple_rte_array[i]->eref->aliasname) != 0)
3089 foreach(l, initial_rels)
3091 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3093 if (rel->reloptkind == RELOPT_BASEREL)
3095 if (rel->relid != i)
3100 Assert(rel->reloptkind == RELOPT_JOINREL);
3102 if (!bms_is_member(i, rel->relids))
3109 ("Relation name \"%s\" is ambiguous.",
3124 * Return join hint which matches given joinrelids.
3126 static JoinMethodHint *
3127 find_join_hint(Relids joinrelids)
3132 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3134 foreach(l, join_hint)
3136 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3138 if (bms_equal(joinrelids, hint->joinrelids))
3146 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3147 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3149 OuterInnerRels *outer_rels;
3150 OuterInnerRels *inner_rels;
3151 Relids outer_relids;
3152 Relids inner_relids;
3154 JoinMethodHint *hint;
3156 if (outer_inner->relation != NULL)
3158 return bms_make_singleton(
3159 find_relid_aliasname(root, outer_inner->relation,
3161 leading_hint->base.hint_str));
3164 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3165 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3167 outer_relids = OuterInnerJoinCreate(outer_rels,
3173 inner_relids = OuterInnerJoinCreate(inner_rels,
3180 join_relids = bms_add_members(outer_relids, inner_relids);
3182 if (bms_num_members(join_relids) > nbaserel)
3186 * If we don't have join method hint, create new one for the
3187 * join combination with all join methods are enabled.
3189 hint = find_join_hint(join_relids);
3193 * Here relnames is not set, since Relids bitmap is sufficient to
3194 * control paths of this query afterward.
3196 hint = (JoinMethodHint *) JoinMethodHintCreate(
3197 leading_hint->base.hint_str,
3199 HINT_KEYWORD_LEADING);
3200 hint->base.state = HINT_STATE_USED;
3201 hint->nrels = bms_num_members(join_relids);
3202 hint->enforce_mask = ENABLE_ALL_JOIN;
3203 hint->joinrelids = bms_copy(join_relids);
3204 hint->inner_nrels = bms_num_members(inner_relids);
3205 hint->inner_joinrelids = bms_copy(inner_relids);
3207 hstate->join_hint_level[hint->nrels] =
3208 lappend(hstate->join_hint_level[hint->nrels], hint);
3212 hint->inner_nrels = bms_num_members(inner_relids);
3213 hint->inner_joinrelids = bms_copy(inner_relids);
3220 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3221 int nrels, char **relnames)
3224 Relids relids = NULL;
3228 for (j = 0; j < nrels; j++)
3230 relname = relnames[j];
3232 relid = find_relid_aliasname(root, relname, initial_rels,
3236 base->state = HINT_STATE_ERROR;
3239 * the aliasname is not found(relid == 0) or same aliasname was used
3240 * multiple times in a query(relid == -1)
3247 if (bms_is_member(relid, relids))
3249 hint_ereport(base->hint_str,
3250 ("Relation name \"%s\" is duplicated.", relname));
3251 base->state = HINT_STATE_ERROR;
3255 relids = bms_add_member(relids, relid);
3260 * Transform join method hint into handy form.
3262 * - create bitmap of relids from alias names, to make it easier to check
3263 * whether a join path matches a join method hint.
3264 * - add join method hints which are necessary to enforce join order
3265 * specified by Leading hint
3268 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3269 List *initial_rels, JoinMethodHint **join_method_hints)
3277 LeadingHint *lhint = NULL;
3280 * Create bitmap of relids from alias names for each join method hint.
3281 * Bitmaps are more handy than strings in join searching.
3283 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3285 JoinMethodHint *hint = hstate->join_hints[i];
3287 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3290 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3291 initial_rels, hint->nrels, hint->relnames);
3293 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3296 hstate->join_hint_level[hint->nrels] =
3297 lappend(hstate->join_hint_level[hint->nrels], hint);
3301 * Create bitmap of relids from alias names for each rows hint.
3302 * Bitmaps are more handy than strings in join searching.
3304 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3306 RowsHint *hint = hstate->rows_hints[i];
3308 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3311 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3312 initial_rels, hint->nrels, hint->relnames);
3315 /* Do nothing if no Leading hint was supplied. */
3316 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3320 * Decide whether to use Leading hint
3322 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3324 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3327 if (leading_hint->base.state == HINT_STATE_ERROR)
3333 foreach(l, leading_hint->relations)
3335 relname = (char *)lfirst(l);;
3337 relid = find_relid_aliasname(root, relname, initial_rels,
3338 leading_hint->base.hint_str);
3340 leading_hint->base.state = HINT_STATE_ERROR;
3345 if (bms_is_member(relid, relids))
3347 hint_ereport(leading_hint->base.hint_str,
3348 ("Relation name \"%s\" is duplicated.", relname));
3349 leading_hint->base.state = HINT_STATE_ERROR;
3353 relids = bms_add_member(relids, relid);
3356 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3361 hint_ereport(lhint->base.hint_str,
3362 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3363 lhint->base.state = HINT_STATE_DUPLICATION;
3365 leading_hint->base.state = HINT_STATE_USED;
3366 lhint = leading_hint;
3369 /* check to exist Leading hint marked with 'used'. */
3374 * We need join method hints which fit specified join order in every join
3375 * level. For example, Leading(A B C) virtually requires following join
3376 * method hints, if no join method hint supplied:
3378 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3379 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3381 * If we already have join method hint which fits specified join order in
3382 * that join level, we leave it as-is and don't add new hints.
3386 if (lhint->outer_inner == NULL)
3388 foreach(l, lhint->relations)
3390 JoinMethodHint *hint;
3392 relname = (char *)lfirst(l);
3395 * Find relid of the relation which has given name. If we have the
3396 * name given in Leading hint multiple times in the join, nothing to
3399 relid = find_relid_aliasname(root, relname, initial_rels,
3402 /* Create bitmap of relids for current join level. */
3403 joinrelids = bms_add_member(joinrelids, relid);
3406 /* We never have join method hint for single relation. */
3411 * If we don't have join method hint, create new one for the
3412 * join combination with all join methods are enabled.
3414 hint = find_join_hint(joinrelids);
3418 * Here relnames is not set, since Relids bitmap is sufficient
3419 * to control paths of this query afterward.
3421 hint = (JoinMethodHint *) JoinMethodHintCreate(
3422 lhint->base.hint_str,
3424 HINT_KEYWORD_LEADING);
3425 hint->base.state = HINT_STATE_USED;
3426 hint->nrels = njoinrels;
3427 hint->enforce_mask = ENABLE_ALL_JOIN;
3428 hint->joinrelids = bms_copy(joinrelids);
3431 join_method_hints[njoinrels] = hint;
3433 if (njoinrels >= nbaserel)
3436 bms_free(joinrelids);
3442 * Delete all join hints which have different combination from Leading
3445 for (i = 2; i <= njoinrels; i++)
3447 list_free(hstate->join_hint_level[i]);
3449 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3454 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3461 njoinrels = bms_num_members(joinrelids);
3462 Assert(njoinrels >= 2);
3465 * Delete all join hints which have different combination from Leading
3468 for (i = 2;i <= njoinrels; i++)
3470 if (hstate->join_hint_level[i] != NIL)
3472 ListCell *prev = NULL;
3473 ListCell *next = NULL;
3474 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3477 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3481 if (hint->inner_nrels == 0 &&
3482 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3483 bms_equal(bms_union(hint->joinrelids, joinrelids),
3486 hstate->join_hint_level[i] =
3487 list_delete_cell(hstate->join_hint_level[i], l,
3496 bms_free(joinrelids);
3499 if (hint_state_enabled(lhint))
3501 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3508 * set_plain_rel_pathlist
3509 * Build access paths for a plain relation (no subquery, no inheritance)
3511 * This function was copied and edited from set_plain_rel_pathlist() in
3512 * src/backend/optimizer/path/allpaths.c
3515 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3517 /* Consider sequential scan */
3518 add_path(rel, create_seqscan_path(root, rel, NULL));
3520 /* Consider index scans */
3521 create_index_paths(root, rel);
3523 /* Consider TID scans */
3524 create_tidscan_paths(root, rel);
3526 /* Now find the cheapest of the paths for this rel */
3531 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3536 foreach(l, initial_rels)
3538 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3540 ScanMethodHint *hint;
3542 /* Skip relations which we can't choose scan method. */
3543 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3546 rte = root->simple_rte_array[rel->relid];
3548 /* We can't force scan method of foreign tables */
3549 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3553 * Create scan paths with GUC parameters which are at the beginning of
3554 * planner if scan method hint is not specified, otherwise use
3555 * specified hints and mark the hint as used.
3557 if ((hint = find_scan_hint(root, rel->relid, rel)) == NULL)
3558 set_scan_config_options(hstate->init_scan_mask,
3562 set_scan_config_options(hint->enforce_mask, hstate->context);
3563 hint->base.state = HINT_STATE_USED;
3566 list_free_deep(rel->pathlist);
3567 rel->pathlist = NIL;
3570 /* It's an "append relation", process accordingly */
3571 set_append_rel_pathlist(root, rel, rel->relid, rte);
3575 set_plain_rel_pathlist(root, rel, rte);
3580 * Restore the GUC variables we set above.
3582 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3586 * wrapper of make_join_rel()
3588 * call make_join_rel() after changing enable_* parameters according to given
3592 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3595 JoinMethodHint *hint;
3599 joinrelids = bms_union(rel1->relids, rel2->relids);
3600 hint = find_join_hint(joinrelids);
3601 bms_free(joinrelids);
3604 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3606 if (hint->inner_nrels == 0)
3608 save_nestlevel = NewGUCNestLevel();
3610 set_join_config_options(hint->enforce_mask, current_hint->context);
3612 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3613 hint->base.state = HINT_STATE_USED;
3616 * Restore the GUC variables we set above.
3618 AtEOXact_GUC(true, save_nestlevel);
3621 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3630 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3631 RelOptInfo *joinrel,
3632 RelOptInfo *outerrel,
3633 RelOptInfo *innerrel,
3635 SpecialJoinInfo *sjinfo,
3638 ScanMethodHint *scan_hint = NULL;
3640 JoinMethodHint *join_hint;
3643 if ((scan_hint = find_scan_hint(root, innerrel->relid, innerrel)) != NULL)
3645 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3646 scan_hint->base.state = HINT_STATE_USED;
3649 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3650 join_hint = find_join_hint(joinrelids);
3651 bms_free(joinrelids);
3653 if (join_hint && join_hint->inner_nrels != 0)
3655 save_nestlevel = NewGUCNestLevel();
3657 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3660 set_join_config_options(join_hint->enforce_mask,
3661 current_hint->context);
3663 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3664 sjinfo, restrictlist);
3665 join_hint->base.state = HINT_STATE_USED;
3669 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3670 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3671 sjinfo, restrictlist);
3675 * Restore the GUC variables we set above.
3677 AtEOXact_GUC(true, save_nestlevel);
3680 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3681 sjinfo, restrictlist);
3683 if (scan_hint != NULL)
3684 set_scan_config_options(current_hint->init_scan_mask,
3685 current_hint->context);
3689 get_num_baserels(List *initial_rels)
3694 foreach(l, initial_rels)
3696 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3698 if (rel->reloptkind == RELOPT_BASEREL)
3700 else if (rel->reloptkind ==RELOPT_JOINREL)
3701 nbaserel+= bms_num_members(rel->relids);
3704 /* other values not expected here */
3705 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3713 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3716 JoinMethodHint **join_method_hints;
3720 bool leading_hint_enable;
3723 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3724 * valid hint is supplied or current nesting depth is nesting depth of SPI
3727 if (!current_hint || nested_level > 0)
3729 if (prev_join_search)
3730 return (*prev_join_search) (root, levels_needed, initial_rels);
3731 else if (enable_geqo && levels_needed >= geqo_threshold)
3732 return geqo(root, levels_needed, initial_rels);
3734 return standard_join_search(root, levels_needed, initial_rels);
3737 /* We apply scan method hint rebuild scan path. */
3738 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3741 * In the case using GEQO, only scan method hints and Set hints have
3742 * effect. Join method and join order is not controllable by hints.
3744 if (enable_geqo && levels_needed >= geqo_threshold)
3745 return geqo(root, levels_needed, initial_rels);
3747 nbaserel = get_num_baserels(initial_rels);
3748 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3749 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3751 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3752 initial_rels, join_method_hints);
3754 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3756 for (i = 2; i <= nbaserel; i++)
3758 list_free(current_hint->join_hint_level[i]);
3760 /* free Leading hint only */
3761 if (join_method_hints[i] != NULL &&
3762 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3763 JoinMethodHintDelete(join_method_hints[i]);
3765 pfree(current_hint->join_hint_level);
3766 pfree(join_method_hints);
3768 if (leading_hint_enable)
3769 set_join_config_options(current_hint->init_join_mask,
3770 current_hint->context);
3777 * Build access paths for a base relation
3779 * This function was copied and edited from set_rel_pathlist() in
3780 * src/backend/optimizer/path/allpaths.c
3783 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3784 Index rti, RangeTblEntry *rte)
3786 if (IS_DUMMY_REL(rel))
3788 /* We already proved the relation empty, so nothing more to do */
3792 /* It's an "append relation", process accordingly */
3793 set_append_rel_pathlist(root, rel, rti, rte);
3797 if (rel->rtekind == RTE_RELATION)
3799 if (rte->relkind == RELKIND_RELATION)
3801 /* Plain relation */
3802 set_plain_rel_pathlist(root, rel, rte);
3805 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3808 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3813 * stmt_beg callback is called when each query in PL/pgSQL function is about
3814 * to be executed. At that timing, we save query string in the global variable
3815 * plpgsql_query_string to use it in planner hook. It's safe to use one global
3816 * variable for the purpose, because its content is only necessary until
3817 * planner hook is called for the query, so recursive PL/pgSQL function calls
3818 * don't harm this mechanism.
3821 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3823 PLpgSQL_expr *expr = NULL;
3825 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
3827 case PLPGSQL_STMT_FORS:
3828 expr = ((PLpgSQL_stmt_fors *) stmt)->query;
3830 case PLPGSQL_STMT_FORC:
3831 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_forc *)stmt)->curvar]))->cursor_explicit_expr;
3833 case PLPGSQL_STMT_RETURN_QUERY:
3834 if (((PLpgSQL_stmt_return_query *) stmt)->query != NULL)
3835 expr = ((PLpgSQL_stmt_return_query *) stmt)->query;
3837 expr = ((PLpgSQL_stmt_return_query *) stmt)->dynquery;
3839 case PLPGSQL_STMT_EXECSQL:
3840 expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3842 case PLPGSQL_STMT_DYNEXECUTE:
3843 expr = ((PLpgSQL_stmt_dynexecute *) stmt)->query;
3845 case PLPGSQL_STMT_DYNFORS:
3846 expr = ((PLpgSQL_stmt_dynfors *) stmt)->query;
3848 case PLPGSQL_STMT_OPEN:
3849 if (((PLpgSQL_stmt_open *) stmt)->query != NULL)
3850 expr = ((PLpgSQL_stmt_open *) stmt)->query;
3851 else if (((PLpgSQL_stmt_open *) stmt)->dynquery != NULL)
3852 expr = ((PLpgSQL_stmt_open *) stmt)->dynquery;
3854 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_open *)stmt)->curvar]))->cursor_explicit_expr;
3861 plpgsql_query_string = expr->query;
3865 * stmt_end callback is called then each query in PL/pgSQL function has
3866 * finished. At that timing, we clear plpgsql_query_string to tell planner
3867 * hook that next call is not for a query written in PL/pgSQL block.
3870 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3872 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3873 plpgsql_query_string = NULL;
3876 #define standard_join_search pg_hint_plan_standard_join_search
3877 #define join_search_one_level pg_hint_plan_join_search_one_level
3878 #define make_join_rel make_join_rel_wrapper
3881 #undef make_join_rel
3882 #define make_join_rel pg_hint_plan_make_join_rel
3883 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3884 #include "make_join_rel.c"
3886 #include "pg_stat_statements.c"