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 Oid parent_rel_oid; /* inherit parent table relid */
310 ScanMethodHint *parent_hint; /* inherit parent table scan hint */
311 List *parent_index_infos; /* information of inherit parent table's
314 /* for join method hints */
315 JoinMethodHint **join_hints; /* parsed join hints */
316 int init_join_mask; /* initial value join parameter */
317 List **join_hint_level;
319 /* for Leading hint */
320 LeadingHint **leading_hint; /* parsed Leading hints */
323 SetHint **set_hints; /* parsed Set hints */
324 GucContext context; /* which GUC parameters can we set? */
327 RowsHint **rows_hints; /* parsed Rows hints */
331 * Describes a hint parser module which is bound with particular hint keyword.
333 typedef struct HintParser
336 HintCreateFunction create_func;
337 HintKeyword hint_keyword;
340 /* Module callbacks */
344 static void push_hint(HintState *hstate);
345 static void pop_hint(void);
347 static void pg_hint_plan_ProcessUtility(Node *parsetree,
348 const char *queryString,
349 ProcessUtilityContext context,
350 ParamListInfo params,
351 DestReceiver *dest, char *completionTag);
352 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
353 ParamListInfo boundParams);
354 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
355 Oid relationObjectId,
356 bool inhparent, RelOptInfo *rel);
357 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
361 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
362 HintKeyword hint_keyword);
363 static void ScanMethodHintDelete(ScanMethodHint *hint);
364 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
365 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
366 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
367 Query *parse, const char *str);
368 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
369 HintKeyword hint_keyword);
370 static void JoinMethodHintDelete(JoinMethodHint *hint);
371 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
372 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
373 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
374 Query *parse, const char *str);
375 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
376 HintKeyword hint_keyword);
377 static void LeadingHintDelete(LeadingHint *hint);
378 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
379 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
380 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
381 Query *parse, const char *str);
382 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
383 HintKeyword hint_keyword);
384 static void SetHintDelete(SetHint *hint);
385 static void SetHintDesc(SetHint *hint, StringInfo buf);
386 static int SetHintCmp(const SetHint *a, const SetHint *b);
387 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
389 static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
390 HintKeyword hint_keyword);
391 static void RowsHintDelete(RowsHint *hint);
392 static void RowsHintDesc(RowsHint *hint, StringInfo buf);
393 static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
394 static const char *RowsHintParse(RowsHint *hint, HintState *hstate,
395 Query *parse, const char *str);
396 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
397 HintKeyword hint_keyword);
399 static void quote_value(StringInfo buf, const char *value);
401 static const char *parse_quoted_value(const char *str, char **word,
404 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
407 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
408 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
409 ListCell *other_rels);
410 static void make_rels_by_clauseless_joins(PlannerInfo *root,
412 ListCell *other_rels);
413 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
414 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
415 Index rti, RangeTblEntry *rte);
416 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
417 List *live_childrels,
418 List *all_child_pathkeys);
419 static Path *get_cheapest_parameterized_child_path(PlannerInfo *root,
421 Relids required_outer);
422 static List *accumulate_append_subpath(List *subpaths, Path *path);
423 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
426 static void pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate,
428 static void pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate,
432 static bool pg_hint_plan_enable_hint = true;
433 static bool pg_hint_plan_debug_print = false;
434 static int pg_hint_plan_parse_messages = INFO;
435 /* Default is off, to keep backward compatibility. */
436 static bool pg_hint_plan_enable_hint_table = false;
438 static const struct config_enum_entry parse_messages_level_options[] = {
439 {"debug", DEBUG2, true},
440 {"debug5", DEBUG5, false},
441 {"debug4", DEBUG4, false},
442 {"debug3", DEBUG3, false},
443 {"debug2", DEBUG2, false},
444 {"debug1", DEBUG1, false},
446 {"info", INFO, false},
447 {"notice", NOTICE, false},
448 {"warning", WARNING, false},
449 {"error", ERROR, false},
451 * {"fatal", FATAL, true},
452 * {"panic", PANIC, true},
457 /* Saved hook values in case of unload */
458 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
459 static planner_hook_type prev_planner = NULL;
460 static get_relation_info_hook_type prev_get_relation_info = NULL;
461 static join_search_hook_type prev_join_search = NULL;
463 /* Hold reference to currently active hint */
464 static HintState *current_hint = NULL;
467 * List of hint contexts. We treat the head of the list as the Top of the
468 * context stack, so current_hint always points the first element of this list.
470 static List *HintStateStack = NIL;
473 * Holds statement name during executing EXECUTE command. NULL for other
476 static char *stmt_name = NULL;
478 static const HintParser parsers[] = {
479 {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
480 {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
481 {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
482 {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
483 {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
484 HINT_KEYWORD_BITMAPSCANREGEXP},
485 {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
486 {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
487 {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
488 {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
489 {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
490 {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
491 {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
492 HINT_KEYWORD_INDEXONLYSCANREGEXP},
493 {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
494 {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
495 {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
496 {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
497 {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
498 {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
499 {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
500 {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
501 {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
502 {HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
503 {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
507 * PL/pgSQL plugin for retrieving string representation of each query during
508 * function execution.
510 const char *plpgsql_query_string = NULL;
511 PLpgSQL_plugin plugin_funcs = {
515 pg_hint_plan_plpgsql_stmt_beg,
516 pg_hint_plan_plpgsql_stmt_end,
521 /* Current nesting depth of SPI calls, used to prevent recursive calls */
522 static int nested_level = 0;
525 * Module load callbacks
530 PLpgSQL_plugin **var_ptr;
532 /* Define custom GUC variables. */
533 DefineCustomBoolVariable("pg_hint_plan.enable_hint",
534 "Force planner to use plans specified in the hint comment preceding to the query.",
536 &pg_hint_plan_enable_hint,
544 DefineCustomBoolVariable("pg_hint_plan.debug_print",
545 "Logs results of hint parsing.",
547 &pg_hint_plan_debug_print,
555 DefineCustomEnumVariable("pg_hint_plan.parse_messages",
556 "Message level of parse errors.",
558 &pg_hint_plan_parse_messages,
560 parse_messages_level_options,
567 DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
568 "Force planner to not get hint by using table lookups.",
570 &pg_hint_plan_enable_hint_table,
579 prev_ProcessUtility = ProcessUtility_hook;
580 ProcessUtility_hook = pg_hint_plan_ProcessUtility;
581 prev_planner = planner_hook;
582 planner_hook = pg_hint_plan_planner;
583 prev_get_relation_info = get_relation_info_hook;
584 get_relation_info_hook = pg_hint_plan_get_relation_info;
585 prev_join_search = join_search_hook;
586 join_search_hook = pg_hint_plan_join_search;
588 /* setup PL/pgSQL plugin hook */
589 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
590 *var_ptr = &plugin_funcs;
594 * Module unload callback
600 PLpgSQL_plugin **var_ptr;
602 /* Uninstall hooks. */
603 ProcessUtility_hook = prev_ProcessUtility;
604 planner_hook = prev_planner;
605 get_relation_info_hook = prev_get_relation_info;
606 join_search_hook = prev_join_search;
608 /* uninstall PL/pgSQL plugin hook */
609 var_ptr = (PLpgSQL_plugin **) find_rendezvous_variable("PLpgSQL_plugin");
614 * create and delete functions the hint object
618 ScanMethodHintCreate(const char *hint_str, const char *keyword,
619 HintKeyword hint_keyword)
621 ScanMethodHint *hint;
623 hint = palloc(sizeof(ScanMethodHint));
624 hint->base.hint_str = hint_str;
625 hint->base.keyword = keyword;
626 hint->base.hint_keyword = hint_keyword;
627 hint->base.type = HINT_TYPE_SCAN_METHOD;
628 hint->base.state = HINT_STATE_NOTUSED;
629 hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
630 hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
631 hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
632 hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
633 hint->relname = NULL;
634 hint->indexnames = NIL;
635 hint->regexp = false;
636 hint->enforce_mask = 0;
638 return (Hint *) hint;
642 ScanMethodHintDelete(ScanMethodHint *hint)
648 pfree(hint->relname);
649 list_free_deep(hint->indexnames);
654 JoinMethodHintCreate(const char *hint_str, const char *keyword,
655 HintKeyword hint_keyword)
657 JoinMethodHint *hint;
659 hint = palloc(sizeof(JoinMethodHint));
660 hint->base.hint_str = hint_str;
661 hint->base.keyword = keyword;
662 hint->base.hint_keyword = hint_keyword;
663 hint->base.type = HINT_TYPE_JOIN_METHOD;
664 hint->base.state = HINT_STATE_NOTUSED;
665 hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
666 hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
667 hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
668 hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
670 hint->inner_nrels = 0;
671 hint->relnames = NULL;
672 hint->enforce_mask = 0;
673 hint->joinrelids = NULL;
674 hint->inner_joinrelids = NULL;
676 return (Hint *) hint;
680 JoinMethodHintDelete(JoinMethodHint *hint)
689 for (i = 0; i < hint->nrels; i++)
690 pfree(hint->relnames[i]);
691 pfree(hint->relnames);
694 bms_free(hint->joinrelids);
695 bms_free(hint->inner_joinrelids);
700 LeadingHintCreate(const char *hint_str, const char *keyword,
701 HintKeyword hint_keyword)
705 hint = palloc(sizeof(LeadingHint));
706 hint->base.hint_str = hint_str;
707 hint->base.keyword = keyword;
708 hint->base.hint_keyword = hint_keyword;
709 hint->base.type = HINT_TYPE_LEADING;
710 hint->base.state = HINT_STATE_NOTUSED;
711 hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
712 hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
713 hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
714 hint->base.parse_func = (HintParseFunction) LeadingHintParse;
715 hint->relations = NIL;
716 hint->outer_inner = NULL;
718 return (Hint *) hint;
722 LeadingHintDelete(LeadingHint *hint)
727 list_free_deep(hint->relations);
728 if (hint->outer_inner)
729 pfree(hint->outer_inner);
734 SetHintCreate(const char *hint_str, const char *keyword,
735 HintKeyword hint_keyword)
739 hint = palloc(sizeof(SetHint));
740 hint->base.hint_str = hint_str;
741 hint->base.keyword = keyword;
742 hint->base.hint_keyword = hint_keyword;
743 hint->base.type = HINT_TYPE_SET;
744 hint->base.state = HINT_STATE_NOTUSED;
745 hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
746 hint->base.desc_func = (HintDescFunction) SetHintDesc;
747 hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
748 hint->base.parse_func = (HintParseFunction) SetHintParse;
753 return (Hint *) hint;
757 SetHintDelete(SetHint *hint)
767 list_free(hint->words);
772 RowsHintCreate(const char *hint_str, const char *keyword,
773 HintKeyword hint_keyword)
777 hint = palloc(sizeof(RowsHint));
778 hint->base.hint_str = hint_str;
779 hint->base.keyword = keyword;
780 hint->base.hint_keyword = hint_keyword;
781 hint->base.type = HINT_TYPE_ROWS;
782 hint->base.state = HINT_STATE_NOTUSED;
783 hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
784 hint->base.desc_func = (HintDescFunction) RowsHintDesc;
785 hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
786 hint->base.parse_func = (HintParseFunction) RowsHintParse;
788 hint->inner_nrels = 0;
789 hint->relnames = NULL;
790 hint->joinrelids = NULL;
791 hint->inner_joinrelids = NULL;
792 hint->rows_str = NULL;
793 hint->value_type = RVT_ABSOLUTE;
796 return (Hint *) hint;
800 RowsHintDelete(RowsHint *hint)
809 for (i = 0; i < hint->nrels; i++)
810 pfree(hint->relnames[i]);
811 pfree(hint->relnames);
814 bms_free(hint->joinrelids);
815 bms_free(hint->inner_joinrelids);
820 HintStateCreate(void)
824 hstate = palloc(sizeof(HintState));
825 hstate->hint_str = NULL;
826 hstate->nall_hints = 0;
827 hstate->max_all_hints = 0;
828 hstate->all_hints = NULL;
829 memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
830 hstate->scan_hints = NULL;
831 hstate->init_scan_mask = 0;
832 hstate->parent_relid = 0;
833 hstate->parent_rel_oid = InvalidOid;
834 hstate->parent_hint = NULL;
835 hstate->parent_index_infos = NIL;
836 hstate->join_hints = NULL;
837 hstate->init_join_mask = 0;
838 hstate->join_hint_level = NULL;
839 hstate->leading_hint = NULL;
840 hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
841 hstate->set_hints = NULL;
842 hstate->rows_hints = NULL;
848 HintStateDelete(HintState *hstate)
855 if (hstate->hint_str)
856 pfree(hstate->hint_str);
858 for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
859 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
860 if (hstate->all_hints)
861 pfree(hstate->all_hints);
862 if (hstate->parent_index_infos)
863 list_free(hstate->parent_index_infos);
867 * Copy given value into buf, with quoting with '"' if necessary.
870 quote_value(StringInfo buf, const char *value)
872 bool need_quote = false;
875 for (str = value; *str != '\0'; str++)
877 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
880 appendStringInfoCharMacro(buf, '"');
885 for (str = value; *str != '\0'; str++)
888 appendStringInfoCharMacro(buf, '"');
890 appendStringInfoCharMacro(buf, *str);
894 appendStringInfoCharMacro(buf, '"');
898 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
902 appendStringInfo(buf, "%s(", hint->base.keyword);
903 if (hint->relname != NULL)
905 quote_value(buf, hint->relname);
906 foreach(l, hint->indexnames)
908 appendStringInfoCharMacro(buf, ' ');
909 quote_value(buf, (char *) lfirst(l));
912 appendStringInfoString(buf, ")\n");
916 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
920 appendStringInfo(buf, "%s(", hint->base.keyword);
921 if (hint->relnames != NULL)
923 quote_value(buf, hint->relnames[0]);
924 for (i = 1; i < hint->nrels; i++)
926 appendStringInfoCharMacro(buf, ' ');
927 quote_value(buf, hint->relnames[i]);
930 appendStringInfoString(buf, ")\n");
935 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
937 if (outer_inner->relation == NULL)
944 appendStringInfoCharMacro(buf, '(');
945 foreach(l, outer_inner->outer_inner_pair)
950 appendStringInfoCharMacro(buf, ' ');
952 OuterInnerDesc(lfirst(l), buf);
955 appendStringInfoCharMacro(buf, ')');
958 quote_value(buf, outer_inner->relation);
962 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
964 appendStringInfo(buf, "%s(", HINT_LEADING);
965 if (hint->outer_inner == NULL)
972 foreach(l, hint->relations)
977 appendStringInfoCharMacro(buf, ' ');
979 quote_value(buf, (char *) lfirst(l));
983 OuterInnerDesc(hint->outer_inner, buf);
985 appendStringInfoString(buf, ")\n");
989 SetHintDesc(SetHint *hint, StringInfo buf)
991 bool is_first = true;
994 appendStringInfo(buf, "%s(", HINT_SET);
995 foreach(l, hint->words)
1000 appendStringInfoCharMacro(buf, ' ');
1002 quote_value(buf, (char *) lfirst(l));
1004 appendStringInfo(buf, ")\n");
1008 RowsHintDesc(RowsHint *hint, StringInfo buf)
1012 appendStringInfo(buf, "%s(", hint->base.keyword);
1013 if (hint->relnames != NULL)
1015 quote_value(buf, hint->relnames[0]);
1016 for (i = 1; i < hint->nrels; i++)
1018 appendStringInfoCharMacro(buf, ' ');
1019 quote_value(buf, hint->relnames[i]);
1022 appendStringInfo(buf, " %s", hint->rows_str);
1023 appendStringInfoString(buf, ")\n");
1028 * Append string which represents all hints in a given state to buf, with
1029 * preceding title with them.
1032 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
1037 appendStringInfo(buf, "%s:\n", title);
1038 for (i = 0; i < hstate->nall_hints; i++)
1040 if (hstate->all_hints[i]->state != state)
1043 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
1048 * Dump contents of given hstate to server log with log level LOG.
1051 HintStateDump(HintState *hstate)
1057 elog(LOG, "pg_hint_plan:\nno hint");
1061 initStringInfo(&buf);
1063 appendStringInfoString(&buf, "pg_hint_plan:\n");
1064 desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
1065 desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
1066 desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
1067 desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
1069 elog(LOG, "%s", buf.data);
1079 RelnameCmp(const void *a, const void *b)
1081 const char *relnamea = *((const char **) a);
1082 const char *relnameb = *((const char **) b);
1084 return strcmp(relnamea, relnameb);
1088 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
1090 return RelnameCmp(&a->relname, &b->relname);
1094 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
1098 if (a->nrels != b->nrels)
1099 return a->nrels - b->nrels;
1101 for (i = 0; i < a->nrels; i++)
1104 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1112 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
1118 SetHintCmp(const SetHint *a, const SetHint *b)
1120 return strcmp(a->name, b->name);
1124 RowsHintCmp(const RowsHint *a, const RowsHint *b)
1128 if (a->nrels != b->nrels)
1129 return a->nrels - b->nrels;
1131 for (i = 0; i < a->nrels; i++)
1134 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
1142 HintCmp(const void *a, const void *b)
1144 const Hint *hinta = *((const Hint **) a);
1145 const Hint *hintb = *((const Hint **) b);
1147 if (hinta->type != hintb->type)
1148 return hinta->type - hintb->type;
1149 if (hinta->state == HINT_STATE_ERROR)
1151 if (hintb->state == HINT_STATE_ERROR)
1153 return hinta->cmp_func(hinta, hintb);
1157 * Returns byte offset of hint b from hint a. If hint a was specified before
1158 * b, positive value is returned.
1161 HintCmpWithPos(const void *a, const void *b)
1163 const Hint *hinta = *((const Hint **) a);
1164 const Hint *hintb = *((const Hint **) b);
1167 result = HintCmp(a, b);
1169 result = hinta->hint_str - hintb->hint_str;
1178 parse_keyword(const char *str, StringInfo buf)
1182 while (!isspace(*str) && *str != '(' && *str != '\0')
1183 appendStringInfoCharMacro(buf, *str++);
1189 skip_parenthesis(const char *str, char parenthesis)
1193 if (*str != parenthesis)
1195 if (parenthesis == '(')
1196 hint_ereport(str, ("Opening parenthesis is necessary."));
1197 else if (parenthesis == ')')
1198 hint_ereport(str, ("Closing parenthesis is necessary."));
1209 * Parse a token from str, and store malloc'd copy into word. A token can be
1210 * quoted with '"'. Return value is pointer to unparsed portion of original
1211 * string, or NULL if an error occurred.
1213 * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1216 parse_quoted_value(const char *str, char **word, bool truncate)
1221 /* Skip leading spaces. */
1224 initStringInfo(&buf);
1237 /* Double quotation must be closed. */
1241 hint_ereport(str, ("Unterminated quoted string."));
1246 * Skip escaped double quotation.
1248 * We don't allow slash-asterisk and asterisk-slash (delimiters of
1249 * block comments) to be an object name, so users must specify
1250 * alias for such object names.
1252 * Those special names can be allowed if we care escaped slashes
1253 * and asterisks, but we don't.
1262 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1266 appendStringInfoCharMacro(&buf, *str++);
1271 hint_ereport(str, ("Zero-length delimited string."));
1278 /* Truncate name if it's too long */
1280 truncate_identifier(buf.data, strlen(buf.data), true);
1287 static OuterInnerRels *
1288 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1290 OuterInnerRels *outer_inner;
1292 outer_inner = palloc(sizeof(OuterInnerRels));
1293 outer_inner->relation = name;
1294 outer_inner->outer_inner_pair = outer_inner_list;
1300 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1302 List *outer_inner_pair = NIL;
1304 if ((str = skip_parenthesis(str, '(')) == NULL)
1309 /* Store words in parentheses into outer_inner_list. */
1310 while(*str != ')' && *str != '\0')
1312 OuterInnerRels *outer_inner_rels;
1316 str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1324 if ((str = parse_quoted_value(str, &name, true)) == NULL)
1327 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1330 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1335 (str = skip_parenthesis(str, ')')) == NULL)
1337 list_free(outer_inner_pair);
1341 *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1347 parse_parentheses_Leading(const char *str, List **name_list,
1348 OuterInnerRels **outer_inner)
1351 bool truncate = true;
1353 if ((str = skip_parenthesis(str, '(')) == NULL)
1359 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1364 /* Store words in parentheses into name_list. */
1365 while(*str != ')' && *str != '\0')
1367 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1369 list_free(*name_list);
1373 *name_list = lappend(*name_list, name);
1378 if ((str = skip_parenthesis(str, ')')) == NULL)
1384 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1387 bool truncate = true;
1389 if ((str = skip_parenthesis(str, '(')) == NULL)
1394 /* Store words in parentheses into name_list. */
1395 while(*str != ')' && *str != '\0')
1397 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1399 list_free(*name_list);
1403 *name_list = lappend(*name_list, name);
1406 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1407 keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1408 keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1409 keyword == HINT_KEYWORD_SET)
1415 if ((str = skip_parenthesis(str, ')')) == NULL)
1421 parse_hints(HintState *hstate, Query *parse, const char *str)
1426 initStringInfo(&buf);
1427 while (*str != '\0')
1429 const HintParser *parser;
1431 /* in error message, we output the comment including the keyword. */
1432 head = (char *) str;
1434 /* parse only the keyword of the hint. */
1435 resetStringInfo(&buf);
1436 str = parse_keyword(str, &buf);
1438 for (parser = parsers; parser->keyword != NULL; parser++)
1440 char *keyword = parser->keyword;
1443 if (strcasecmp(buf.data, keyword) != 0)
1446 hint = parser->create_func(head, keyword, parser->hint_keyword);
1448 /* parser of each hint does parse in a parenthesis. */
1449 if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1451 hint->delete_func(hint);
1457 * Add hint information into all_hints array. If we don't have
1458 * enough space, double the array.
1460 if (hstate->nall_hints == 0)
1462 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1463 hstate->all_hints = (Hint **)
1464 palloc(sizeof(Hint *) * hstate->max_all_hints);
1466 else if (hstate->nall_hints == hstate->max_all_hints)
1468 hstate->max_all_hints *= 2;
1469 hstate->all_hints = (Hint **)
1470 repalloc(hstate->all_hints,
1471 sizeof(Hint *) * hstate->max_all_hints);
1474 hstate->all_hints[hstate->nall_hints] = hint;
1475 hstate->nall_hints++;
1482 if (parser->keyword == NULL)
1485 ("Unrecognized hint keyword \"%s\".", buf.data));
1496 * Get hints from table by client-supplied query string and application name.
1499 get_hints_from_table(const char *client_query, const char *client_application)
1501 const char *search_query =
1503 " FROM hint_plan.hints "
1504 " WHERE norm_query_string = $1 "
1505 " AND ( application_name = $2 "
1506 " OR application_name = '' ) "
1507 " ORDER BY application_name DESC";
1508 static SPIPlanPtr plan = NULL;
1510 Oid argtypes[2] = { TEXTOID, TEXTOID };
1512 bool nulls[2] = { false, false };
1525 p = SPI_prepare(search_query, 2, argtypes);
1526 plan = SPI_saveplan(p);
1530 qry = cstring_to_text(client_query);
1531 app = cstring_to_text(client_application);
1532 values[0] = PointerGetDatum(qry);
1533 values[1] = PointerGetDatum(app);
1535 SPI_execute_plan(plan, values, nulls, true, 1);
1537 if (SPI_processed > 0)
1541 hints = SPI_getvalue(SPI_tuptable->vals[0],
1542 SPI_tuptable->tupdesc, 1);
1544 * Here we use SPI_palloc to ensure that hints string is valid even
1545 * after SPI_finish call. We can't use simple palloc because it
1546 * allocates memory in SPI's context and that context is deleted in
1549 buf = SPI_palloc(strlen(hints) + 1);
1569 * Get client-supplied query string.
1572 get_query_string(void)
1578 PreparedStatement *entry;
1580 entry = FetchPreparedStatement(stmt_name, true);
1581 p = entry->plansource->query_string;
1583 else if (plpgsql_query_string)
1584 p = plpgsql_query_string;
1586 p = debug_query_string;
1592 * Get hints from the head block comment in client-supplied query string.
1595 get_hints_from_comment(const char *p)
1597 const char *hint_head;
1605 /* extract query head comment. */
1606 hint_head = strstr(p, HINT_START);
1607 if (hint_head == NULL)
1609 for (;p < hint_head; p++)
1612 * Allow these characters precedes hint comment:
1614 * - alphabets which are in ASCII range
1615 * - space, tabs and new-lines
1616 * - underscores, for identifier
1617 * - commas, for SELECT clause, EXPLAIN and PREPARE
1618 * - parentheses, for EXPLAIN and PREPARE
1620 * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1621 * avoid behavior which depends on locale setting.
1623 if (!(*p >= '0' && *p <= '9') &&
1624 !(*p >= 'A' && *p <= 'Z') &&
1625 !(*p >= 'a' && *p <= 'z') &&
1629 *p != '(' && *p != ')')
1633 len = strlen(HINT_START);
1638 /* find hint end keyword. */
1639 if ((tail = strstr(p, HINT_END)) == NULL)
1641 hint_ereport(head, ("Unterminated block comment."));
1645 /* We don't support nested block comments. */
1646 if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1648 hint_ereport(head, ("Nested block comments are not supported."));
1652 /* Make a copy of hint. */
1654 head = palloc(len + 1);
1655 memcpy(head, p, len);
1663 * Parse hints that got, create hint struct from parse tree and parse hints.
1666 create_hintstate(Query *parse, const char *hints)
1676 hstate = HintStateCreate();
1677 hstate->hint_str = (char *) hints;
1679 /* parse each hint. */
1680 parse_hints(hstate, parse, p);
1682 /* When nothing specified a hint, we free HintState and returns NULL. */
1683 if (hstate->nall_hints == 0)
1685 HintStateDelete(hstate);
1689 /* Sort hints in order of original position. */
1690 qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1693 /* Count number of hints per hint-type. */
1694 for (i = 0; i < hstate->nall_hints; i++)
1696 Hint *cur_hint = hstate->all_hints[i];
1697 hstate->num_hints[cur_hint->type]++;
1701 * If an object (or a set of objects) has multiple hints of same hint-type,
1702 * only the last hint is valid and others are ignored in planning.
1703 * Hints except the last are marked as 'duplicated' to remember the order.
1705 for (i = 0; i < hstate->nall_hints - 1; i++)
1707 Hint *cur_hint = hstate->all_hints[i];
1708 Hint *next_hint = hstate->all_hints[i + 1];
1711 * Leading hint is marked as 'duplicated' in transform_join_hints.
1713 if (cur_hint->type == HINT_TYPE_LEADING &&
1714 next_hint->type == HINT_TYPE_LEADING)
1718 * Note that we need to pass addresses of hint pointers, because
1719 * HintCmp is designed to sort array of Hint* by qsort.
1721 if (HintCmp(&cur_hint, &next_hint) == 0)
1723 hint_ereport(cur_hint->hint_str,
1724 ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1725 cur_hint->state = HINT_STATE_DUPLICATION;
1730 * Make sure that per-type array pointers point proper position in the
1731 * array which consists of all hints.
1733 hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1734 hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1735 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1736 hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1737 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1738 hstate->set_hints = (SetHint **) (hstate->leading_hint +
1739 hstate->num_hints[HINT_TYPE_LEADING]);
1740 hstate->rows_hints = (RowsHint **) (hstate->set_hints +
1741 hstate->num_hints[HINT_TYPE_SET]);
1747 * Parse inside of parentheses of scan-method hints.
1750 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1753 const char *keyword = hint->base.keyword;
1754 HintKeyword hint_keyword = hint->base.hint_keyword;
1755 List *name_list = NIL;
1758 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1761 /* Parse relation name and index name(s) if given hint accepts. */
1762 length = list_length(name_list);
1765 hint->relname = linitial(name_list);
1766 hint->indexnames = list_delete_first(name_list);
1768 /* check whether the hint accepts index name(s). */
1770 hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1771 hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1772 hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1773 hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1774 hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1775 hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1778 ("%s hint accepts only one relation.",
1779 hint->base.keyword));
1780 hint->base.state = HINT_STATE_ERROR;
1787 ("%s hint requires a relation.",
1788 hint->base.keyword));
1789 hint->base.state = HINT_STATE_ERROR;
1793 /* Set a bit for specified hint. */
1794 switch (hint_keyword)
1796 case HINT_KEYWORD_SEQSCAN:
1797 hint->enforce_mask = ENABLE_SEQSCAN;
1799 case HINT_KEYWORD_INDEXSCAN:
1800 hint->enforce_mask = ENABLE_INDEXSCAN;
1802 case HINT_KEYWORD_INDEXSCANREGEXP:
1803 hint->enforce_mask = ENABLE_INDEXSCAN;
1804 hint->regexp = true;
1806 case HINT_KEYWORD_BITMAPSCAN:
1807 hint->enforce_mask = ENABLE_BITMAPSCAN;
1809 case HINT_KEYWORD_BITMAPSCANREGEXP:
1810 hint->enforce_mask = ENABLE_BITMAPSCAN;
1811 hint->regexp = true;
1813 case HINT_KEYWORD_TIDSCAN:
1814 hint->enforce_mask = ENABLE_TIDSCAN;
1816 case HINT_KEYWORD_NOSEQSCAN:
1817 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1819 case HINT_KEYWORD_NOINDEXSCAN:
1820 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1822 case HINT_KEYWORD_NOBITMAPSCAN:
1823 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1825 case HINT_KEYWORD_NOTIDSCAN:
1826 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1828 case HINT_KEYWORD_INDEXONLYSCAN:
1829 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1831 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1832 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1833 hint->regexp = true;
1835 case HINT_KEYWORD_NOINDEXONLYSCAN:
1836 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1839 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1848 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1851 const char *keyword = hint->base.keyword;
1852 HintKeyword hint_keyword = hint->base.hint_keyword;
1853 List *name_list = NIL;
1855 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1858 hint->nrels = list_length(name_list);
1860 if (hint->nrels > 0)
1866 * Transform relation names from list to array to sort them with qsort
1869 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1870 foreach (l, name_list)
1872 hint->relnames[i] = lfirst(l);
1877 list_free(name_list);
1879 /* A join hint requires at least two relations */
1880 if (hint->nrels < 2)
1883 ("%s hint requires at least two relations.",
1884 hint->base.keyword));
1885 hint->base.state = HINT_STATE_ERROR;
1889 /* Sort hints in alphabetical order of relation names. */
1890 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1892 switch (hint_keyword)
1894 case HINT_KEYWORD_NESTLOOP:
1895 hint->enforce_mask = ENABLE_NESTLOOP;
1897 case HINT_KEYWORD_MERGEJOIN:
1898 hint->enforce_mask = ENABLE_MERGEJOIN;
1900 case HINT_KEYWORD_HASHJOIN:
1901 hint->enforce_mask = ENABLE_HASHJOIN;
1903 case HINT_KEYWORD_NONESTLOOP:
1904 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1906 case HINT_KEYWORD_NOMERGEJOIN:
1907 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1909 case HINT_KEYWORD_NOHASHJOIN:
1910 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1913 hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1922 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1925 if (outer_inner->outer_inner_pair == NIL)
1927 if (outer_inner->relation)
1933 if (list_length(outer_inner->outer_inner_pair) == 2)
1935 foreach(l, outer_inner->outer_inner_pair)
1937 if (!OuterInnerPairCheck(lfirst(l)))
1948 OuterInnerList(OuterInnerRels *outer_inner)
1950 List *outer_inner_list = NIL;
1952 OuterInnerRels *outer_inner_rels;
1954 foreach(l, outer_inner->outer_inner_pair)
1956 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1958 if (outer_inner_rels->relation != NULL)
1959 outer_inner_list = lappend(outer_inner_list,
1960 outer_inner_rels->relation);
1962 outer_inner_list = list_concat(outer_inner_list,
1963 OuterInnerList(outer_inner_rels));
1965 return outer_inner_list;
1969 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1972 List *name_list = NIL;
1973 OuterInnerRels *outer_inner = NULL;
1975 if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1979 if (outer_inner != NULL)
1980 name_list = OuterInnerList(outer_inner);
1982 hint->relations = name_list;
1983 hint->outer_inner = outer_inner;
1985 /* A Leading hint requires at least two relations */
1986 if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1988 hint_ereport(hint->base.hint_str,
1989 ("%s hint requires at least two relations.",
1991 hint->base.state = HINT_STATE_ERROR;
1993 else if (hint->outer_inner != NULL &&
1994 !OuterInnerPairCheck(hint->outer_inner))
1996 hint_ereport(hint->base.hint_str,
1997 ("%s hint requires two sets of relations when parentheses nests.",
1999 hint->base.state = HINT_STATE_ERROR;
2006 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
2008 List *name_list = NIL;
2010 if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
2014 hint->words = name_list;
2016 /* We need both name and value to set GUC parameter. */
2017 if (list_length(name_list) == 2)
2019 hint->name = linitial(name_list);
2020 hint->value = lsecond(name_list);
2024 hint_ereport(hint->base.hint_str,
2025 ("%s hint requires name and value of GUC parameter.",
2027 hint->base.state = HINT_STATE_ERROR;
2034 RowsHintParse(RowsHint *hint, HintState *hstate, Query *parse,
2037 HintKeyword hint_keyword = hint->base.hint_keyword;
2038 List *name_list = NIL;
2042 if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
2045 /* Last element must be rows specification */
2046 hint->nrels = list_length(name_list) - 1;
2048 if (hint->nrels > 0)
2054 * Transform relation names from list to array to sort them with qsort
2057 hint->relnames = palloc(sizeof(char *) * hint->nrels);
2058 foreach (l, name_list)
2060 if (hint->nrels <= i)
2062 hint->relnames[i] = lfirst(l);
2067 /* Retieve rows estimation */
2068 rows_str = list_nth(name_list, hint->nrels);
2069 hint->rows_str = rows_str; /* store as-is for error logging */
2070 if (rows_str[0] == '#')
2072 hint->value_type = RVT_ABSOLUTE;
2075 else if (rows_str[0] == '+')
2077 hint->value_type = RVT_ADD;
2080 else if (rows_str[0] == '-')
2082 hint->value_type = RVT_SUB;
2085 else if (rows_str[0] == '*')
2087 hint->value_type = RVT_MULTI;
2092 hint_ereport(rows_str, ("Unrecognized rows value type notation."));
2093 hint->base.state = HINT_STATE_ERROR;
2096 hint->rows = strtod(rows_str, &end_ptr);
2099 hint_ereport(rows_str,
2100 ("%s hint requires valid number as rows estimation.",
2101 hint->base.keyword));
2102 hint->base.state = HINT_STATE_ERROR;
2106 /* A join hint requires at least two relations */
2107 if (hint->nrels < 2)
2110 ("%s hint requires at least two relations.",
2111 hint->base.keyword));
2112 hint->base.state = HINT_STATE_ERROR;
2116 list_free(name_list);
2118 /* Sort relnames in alphabetical order. */
2119 qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
2125 * set GUC parameter functions
2129 set_config_option_wrapper(const char *name, const char *value,
2130 GucContext context, GucSource source,
2131 GucAction action, bool changeVal, int elevel)
2134 MemoryContext ccxt = CurrentMemoryContext;
2138 result = set_config_option(name, value, context, source,
2139 action, changeVal, 0);
2145 /* Save error info */
2146 MemoryContextSwitchTo(ccxt);
2147 errdata = CopyErrorData();
2150 ereport(elevel, (errcode(errdata->sqlerrcode),
2151 errmsg("%s", errdata->message),
2152 errdata->detail ? errdetail("%s", errdata->detail) : 0,
2153 errdata->hint ? errhint("%s", errdata->hint) : 0));
2154 FreeErrorData(errdata);
2162 set_config_options(SetHint **options, int noptions, GucContext context)
2167 save_nestlevel = NewGUCNestLevel();
2169 for (i = 0; i < noptions; i++)
2171 SetHint *hint = options[i];
2174 if (!hint_state_enabled(hint))
2177 result = set_config_option_wrapper(hint->name, hint->value, context,
2178 PGC_S_SESSION, GUC_ACTION_SAVE, true,
2179 pg_hint_plan_parse_messages);
2181 hint->base.state = HINT_STATE_USED;
2183 hint->base.state = HINT_STATE_ERROR;
2186 return save_nestlevel;
2189 #define SET_CONFIG_OPTION(name, type_bits) \
2190 set_config_option_wrapper((name), \
2191 (mask & (type_bits)) ? "true" : "false", \
2192 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
2195 set_scan_config_options(unsigned char enforce_mask, GucContext context)
2199 if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
2200 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
2201 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
2203 mask = enforce_mask;
2205 mask = enforce_mask & current_hint->init_scan_mask;
2207 SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
2208 SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
2209 SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
2210 SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
2211 SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
2215 set_join_config_options(unsigned char enforce_mask, GucContext context)
2219 if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
2220 enforce_mask == ENABLE_HASHJOIN)
2221 mask = enforce_mask;
2223 mask = enforce_mask & current_hint->init_join_mask;
2225 SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
2226 SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
2227 SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
2231 * pg_hint_plan hook functions
2235 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
2236 ProcessUtilityContext context,
2237 ParamListInfo params,
2238 DestReceiver *dest, char *completionTag)
2243 * Use standard planner if pg_hint_plan is disabled or current nesting
2244 * depth is nesting depth of SPI calls.
2246 if (!pg_hint_plan_enable_hint || nested_level > 0)
2248 if (prev_ProcessUtility)
2249 (*prev_ProcessUtility) (parsetree, queryString,
2251 dest, completionTag);
2253 standard_ProcessUtility(parsetree, queryString,
2255 dest, completionTag);
2260 if (IsA(node, ExplainStmt))
2263 * Draw out parse tree of actual query from Query struct of EXPLAIN
2269 stmt = (ExplainStmt *) node;
2271 Assert(IsA(stmt->query, Query));
2272 query = (Query *) stmt->query;
2274 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2275 node = query->utilityStmt;
2279 * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2280 * specified to preceding PREPARE command to use it as source of hints.
2282 if (IsA(node, ExecuteStmt))
2286 stmt = (ExecuteStmt *) node;
2287 stmt_name = stmt->name;
2291 * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2294 if (IsA(node, CreateTableAsStmt))
2296 CreateTableAsStmt *stmt;
2299 stmt = (CreateTableAsStmt *) node;
2300 Assert(IsA(stmt->query, Query));
2301 query = (Query *) stmt->query;
2303 if (query->commandType == CMD_UTILITY &&
2304 IsA(query->utilityStmt, ExecuteStmt))
2306 ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2307 stmt_name = estmt->name;
2315 if (prev_ProcessUtility)
2316 (*prev_ProcessUtility) (parsetree, queryString,
2318 dest, completionTag);
2320 standard_ProcessUtility(parsetree, queryString,
2322 dest, completionTag);
2336 if (prev_ProcessUtility)
2337 (*prev_ProcessUtility) (parsetree, queryString,
2339 dest, completionTag);
2341 standard_ProcessUtility(parsetree, queryString,
2343 dest, completionTag);
2347 * Push a hint into hint stack which is implemented with List struct. Head of
2348 * list is top of stack.
2351 push_hint(HintState *hstate)
2353 /* Prepend new hint to the list means pushing to stack. */
2354 HintStateStack = lcons(hstate, HintStateStack);
2356 /* Pushed hint is the one which should be used hereafter. */
2357 current_hint = hstate;
2360 /* Pop a hint from hint stack. Popped hint is automatically discarded. */
2364 /* Hint stack must not be empty. */
2365 if(HintStateStack == NIL)
2366 elog(ERROR, "hint stack is empty");
2369 * Take a hint at the head from the list, and free it. Switch current_hint
2370 * to point new head (NULL if the list is empty).
2372 HintStateStack = list_delete_first(HintStateStack);
2373 HintStateDelete(current_hint);
2374 if(HintStateStack == NIL)
2375 current_hint = NULL;
2377 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2380 static PlannedStmt *
2381 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2383 const char *hints = NULL;
2386 pgssJumbleState jstate;
2389 PlannedStmt *result;
2393 * Use standard planner if pg_hint_plan is disabled or current nesting
2394 * depth is nesting depth of SPI calls. Other hook functions try to change
2395 * plan with current_hint if any, so set it to NULL.
2397 if (!pg_hint_plan_enable_hint || nested_level > 0)
2398 goto standard_planner_proc;
2400 /* Create hint struct from client-supplied query string. */
2401 query = get_query_string();
2404 * Create hintstate from hint specified for the query, if any.
2406 * First we lookup hint in pg_hint.hints table by normalized query string,
2407 * unless pg_hint_plan.enable_hint_table is OFF.
2408 * This parameter provides option to avoid overhead of table lookup during
2411 * If no hint was found, then we try to get hint from special query comment.
2413 if (pg_hint_plan_enable_hint_table)
2416 * Search hint information which is stored for the query and the
2417 * application. Query string is normalized before using in condition
2418 * in order to allow fuzzy matching.
2420 * XXX: normalizing code is copied from pg_stat_statements.c, so be
2421 * careful when supporting PostgreSQL's version up.
2423 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
2424 jstate.jumble_len = 0;
2425 jstate.clocations_buf_size = 32;
2426 jstate.clocations = (pgssLocationLen *)
2427 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
2428 jstate.clocations_count = 0;
2429 JumbleQuery(&jstate, parse);
2431 * generate_normalized_query() copies exact given query_len bytes, so we
2432 * add 1 byte for null-termination here. As comments on
2433 * generate_normalized_query says, generate_normalized_query doesn't
2434 * take care of null-terminate, but additional 1 byte ensures that '\0'
2435 * byte in the source buffer to be copied into norm_query.
2437 query_len = strlen(query) + 1;
2438 norm_query = generate_normalized_query(&jstate,
2441 GetDatabaseEncoding());
2442 hints = get_hints_from_table(norm_query, application_name);
2444 "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2445 norm_query, application_name, hints ? hints : "(none)");
2448 hints = get_hints_from_comment(query);
2449 hstate = create_hintstate(parse, hints);
2452 * Use standard planner if the statement has not valid hint. Other hook
2453 * functions try to change plan with current_hint if any, so set it to
2457 goto standard_planner_proc;
2460 * Push new hint struct to the hint stack to disable previous hint context.
2464 /* Set GUC parameters which are specified with Set hint. */
2465 save_nestlevel = set_config_options(current_hint->set_hints,
2466 current_hint->num_hints[HINT_TYPE_SET],
2467 current_hint->context);
2470 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2471 if (enable_indexscan)
2472 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2473 if (enable_bitmapscan)
2474 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2476 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2477 if (enable_indexonlyscan)
2478 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2479 if (enable_nestloop)
2480 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2481 if (enable_mergejoin)
2482 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2483 if (enable_hashjoin)
2484 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2487 * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2488 * state when this planner started when error occurred in planner.
2493 result = (*prev_planner) (parse, cursorOptions, boundParams);
2495 result = standard_planner(parse, cursorOptions, boundParams);
2500 * Rollback changes of GUC parameters, and pop current hint context
2501 * from hint stack to rewind the state.
2503 AtEOXact_GUC(true, save_nestlevel);
2509 /* Print hint in debug mode. */
2510 if (pg_hint_plan_debug_print)
2511 HintStateDump(current_hint);
2514 * Rollback changes of GUC parameters, and pop current hint context from
2515 * hint stack to rewind the state.
2517 AtEOXact_GUC(true, save_nestlevel);
2522 standard_planner_proc:
2523 current_hint = NULL;
2525 return (*prev_planner) (parse, cursorOptions, boundParams);
2527 return standard_planner(parse, cursorOptions, boundParams);
2531 * Return scan method hint which matches given aliasname.
2533 static ScanMethodHint *
2534 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2540 * We can't apply scan method hint if the relation is:
2541 * - not a base relation
2542 * - not an ordinary relation (such as join and subquery)
2544 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2547 rte = root->simple_rte_array[rel->relid];
2549 /* We can't force scan method of foreign tables */
2550 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2553 /* Find scan method hint, which matches given names, from the list. */
2554 for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2556 ScanMethodHint *hint = current_hint->scan_hints[i];
2558 /* We ignore disabled hints. */
2559 if (!hint_state_enabled(hint))
2562 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2572 * Returns TRUE on match, FALSE on no match.
2574 * s1 --- the data to match against
2575 * s2 --- the pattern
2577 * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2580 regexpeq(const char *s1, const char *s2)
2586 strcpy(name.data, s1);
2587 regexp = cstring_to_text(s2);
2589 result = DirectFunctionCall2Coll(nameregexeq,
2590 DEFAULT_COLLATION_OID,
2591 NameGetDatum(&name),
2592 PointerGetDatum(regexp));
2593 return DatumGetBool(result);
2597 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2605 * We delete all the IndexOptInfo list and prevent you from being usable by
2608 if (hint->enforce_mask == ENABLE_SEQSCAN ||
2609 hint->enforce_mask == ENABLE_TIDSCAN)
2611 list_free_deep(rel->indexlist);
2612 rel->indexlist = NIL;
2613 hint->base.state = HINT_STATE_USED;
2619 * When a list of indexes is not specified, we just use all indexes.
2621 if (hint->indexnames == NIL)
2625 * Leaving only an specified index, we delete it from a IndexOptInfo list
2629 if (pg_hint_plan_debug_print)
2630 initStringInfo(&buf);
2632 for (cell = list_head(rel->indexlist); cell; cell = next)
2634 IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
2635 char *indexname = get_rel_name(info->indexoid);
2637 bool use_index = false;
2641 foreach(l, hint->indexnames)
2643 char *hintname = (char *) lfirst(l);
2647 result = regexpeq(indexname, hintname);
2649 result = RelnameCmp(&indexname, &hintname) == 0;
2654 if (pg_hint_plan_debug_print)
2656 appendStringInfoCharMacro(&buf, ' ');
2657 quote_value(&buf, indexname);
2665 * to make the index a candidate when definition of this index is
2666 * matched with the index's definition of current_hint.
2668 if (OidIsValid(relationObjectId) && !use_index)
2670 foreach(l, current_hint->parent_index_infos)
2674 ParentIndexInfo *p_info = (ParentIndexInfo *)lfirst(l);
2676 /* check to match the parameter of unique */
2677 if (p_info->indisunique != info->unique)
2680 /* check to match the parameter of index's method */
2681 if (p_info->method != info->relam)
2684 /* to check to match the indexkey's configuration */
2685 if ((list_length(p_info->column_names)) !=
2689 /* check to match the indexkey's configuration */
2690 for (i = 0; i < info->ncolumns; i++)
2692 char *c_attname = NULL;
2693 char *p_attname = NULL;
2696 list_nth(p_info->column_names, i);
2698 /* both are expressions */
2699 if (info->indexkeys[i] == 0 && !p_attname)
2702 /* one's column is expression, the other is not */
2703 if (info->indexkeys[i] == 0 || !p_attname)
2706 c_attname = get_attname(relationObjectId,
2707 info->indexkeys[i]);
2709 if (strcmp(p_attname, c_attname) != 0)
2712 if (p_info->indcollation[i] != info->indexcollations[i])
2715 if (p_info->opclass[i] != info->opcintype[i])
2718 if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2719 info->reverse_sort[i])
2722 if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2723 info->nulls_first[i])
2728 if (i != info->ncolumns)
2731 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2732 (p_info->indpred_str && (info->indpred != NIL)))
2735 * Fetch the pg_index tuple by the Oid of the index
2737 ht_idx = SearchSysCache1(INDEXRELID,
2738 ObjectIdGetDatum(info->indexoid));
2740 /* check to match the expression's parameter of index */
2741 if (p_info->expression_str &&
2742 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2749 * to change the expression's parameter of child's
2752 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2753 Anum_pg_index_indexprs,
2756 result = DirectFunctionCall2(pg_get_expr,
2761 if (strcmp(p_info->expression_str,
2762 text_to_cstring(DatumGetTextP(result))) != 0)
2765 ReleaseSysCache(ht_idx);
2771 /* Check to match the predicate's parameter of index */
2772 if (p_info->indpred_str &&
2773 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2780 * to change the predicate's parameter of child's
2783 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2784 Anum_pg_index_indpred,
2787 result = DirectFunctionCall2(pg_get_expr,
2792 if (strcmp(p_info->indpred_str,
2793 text_to_cstring(DatumGetTextP(result))) != 0)
2796 ReleaseSysCache(ht_idx);
2803 ReleaseSysCache(ht_idx);
2805 else if (p_info->expression_str || (info->indexprs != NIL))
2807 else if (p_info->indpred_str || (info->indpred != NIL))
2812 /* to log the candidate of index */
2813 if (pg_hint_plan_debug_print)
2815 appendStringInfoCharMacro(&buf, ' ');
2816 quote_value(&buf, indexname);
2824 rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2831 if (pg_hint_plan_debug_print)
2834 StringInfoData rel_buf;
2836 if (OidIsValid(relationObjectId))
2837 relname = get_rel_name(relationObjectId);
2839 relname = hint->relname;
2841 initStringInfo(&rel_buf);
2842 quote_value(&rel_buf, relname);
2845 (errmsg("available indexes for %s(%s):%s",
2850 pfree(rel_buf.data);
2855 * Return information of index definition.
2857 static ParentIndexInfo *
2858 get_parent_index_info(Oid indexoid, Oid relid)
2860 ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2861 Relation indexRelation;
2862 Form_pg_index index;
2866 indexRelation = index_open(indexoid, RowExclusiveLock);
2868 index = indexRelation->rd_index;
2870 p_info->indisunique = index->indisunique;
2871 p_info->method = indexRelation->rd_rel->relam;
2873 p_info->column_names = NIL;
2874 p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2875 p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2876 p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2878 for (i = 0; i < index->indnatts; i++)
2880 attname = get_attname(relid, index->indkey.values[i]);
2881 p_info->column_names = lappend(p_info->column_names, attname);
2883 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2884 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2885 p_info->indoption[i] = indexRelation->rd_indoption[i];
2889 * to check to match the expression's parameter of index with child indexes
2891 p_info->expression_str = NULL;
2892 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2898 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2899 Anum_pg_index_indexprs, &isnull);
2901 result = DirectFunctionCall2(pg_get_expr,
2903 ObjectIdGetDatum(relid));
2905 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2909 * to check to match the predicate's parameter of index with child indexes
2911 p_info->indpred_str = NULL;
2912 if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2918 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2919 Anum_pg_index_indpred, &isnull);
2921 result = DirectFunctionCall2(pg_get_expr,
2923 ObjectIdGetDatum(relid));
2925 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2928 index_close(indexRelation, NoLock);
2934 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2935 bool inhparent, RelOptInfo *rel)
2937 ScanMethodHint *hint;
2939 if (prev_get_relation_info)
2940 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2943 * Do nothing if we don't have valid hint in this context or current
2944 * nesting depth is nesting depth of SPI calls.
2946 if (!current_hint || nested_level > 0)
2951 /* store does relids of parent table. */
2952 current_hint->parent_relid = rel->relid;
2953 current_hint->parent_rel_oid = relationObjectId;
2955 else if (current_hint->parent_relid != 0)
2958 * We use the same GUC parameter if this table is the child table of a
2959 * table called pg_hint_plan_get_relation_info just before that.
2963 /* append_rel_list contains all append rels; ignore others */
2964 foreach(l, root->append_rel_list)
2966 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2968 /* This rel is child table. */
2969 if (appinfo->parent_relid == current_hint->parent_relid &&
2970 appinfo->child_relid == rel->relid)
2972 if (current_hint->parent_hint)
2973 delete_indexes(current_hint->parent_hint, rel,
2980 /* This rel is not inherit table. */
2981 current_hint->parent_relid = 0;
2982 current_hint->parent_rel_oid = InvalidOid;
2983 current_hint->parent_hint = NULL;
2987 * If scan method hint was given, reset GUC parameters which control
2988 * planner behavior about choosing scan methods.
2990 if ((hint = find_scan_hint(root, rel)) == NULL)
2992 set_scan_config_options(current_hint->init_scan_mask,
2993 current_hint->context);
2996 set_scan_config_options(hint->enforce_mask, current_hint->context);
2997 hint->base.state = HINT_STATE_USED;
3005 current_hint->parent_hint = hint;
3007 relation = heap_open(relationObjectId, NoLock);
3008 indexoidlist = RelationGetIndexList(relation);
3010 foreach(l, indexoidlist)
3012 Oid indexoid = lfirst_oid(l);
3013 char *indexname = get_rel_name(indexoid);
3014 bool use_index = false;
3016 ParentIndexInfo *parent_index_info;
3018 foreach(lc, hint->indexnames)
3020 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
3029 parent_index_info = get_parent_index_info(indexoid,
3031 current_hint->parent_index_infos =
3032 lappend(current_hint->parent_index_infos, parent_index_info);
3034 heap_close(relation, NoLock);
3037 delete_indexes(hint, rel, InvalidOid);
3041 * Return index of relation which matches given aliasname, or 0 if not found.
3042 * If same aliasname was used multiple times in a query, return -1.
3045 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
3051 for (i = 1; i < root->simple_rel_array_size; i++)
3055 if (root->simple_rel_array[i] == NULL)
3058 Assert(i == root->simple_rel_array[i]->relid);
3060 if (RelnameCmp(&aliasname,
3061 &root->simple_rte_array[i]->eref->aliasname) != 0)
3064 foreach(l, initial_rels)
3066 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3068 if (rel->reloptkind == RELOPT_BASEREL)
3070 if (rel->relid != i)
3075 Assert(rel->reloptkind == RELOPT_JOINREL);
3077 if (!bms_is_member(i, rel->relids))
3084 ("Relation name \"%s\" is ambiguous.",
3099 * Return join hint which matches given joinrelids.
3101 static JoinMethodHint *
3102 find_join_hint(Relids joinrelids)
3107 join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
3109 foreach(l, join_hint)
3111 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
3113 if (bms_equal(joinrelids, hint->joinrelids))
3121 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
3122 PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
3124 OuterInnerRels *outer_rels;
3125 OuterInnerRels *inner_rels;
3126 Relids outer_relids;
3127 Relids inner_relids;
3129 JoinMethodHint *hint;
3131 if (outer_inner->relation != NULL)
3133 return bms_make_singleton(
3134 find_relid_aliasname(root, outer_inner->relation,
3136 leading_hint->base.hint_str));
3139 outer_rels = lfirst(outer_inner->outer_inner_pair->head);
3140 inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
3142 outer_relids = OuterInnerJoinCreate(outer_rels,
3148 inner_relids = OuterInnerJoinCreate(inner_rels,
3155 join_relids = bms_add_members(outer_relids, inner_relids);
3157 if (bms_num_members(join_relids) > nbaserel)
3161 * If we don't have join method hint, create new one for the
3162 * join combination with all join methods are enabled.
3164 hint = find_join_hint(join_relids);
3168 * Here relnames is not set, since Relids bitmap is sufficient to
3169 * control paths of this query afterward.
3171 hint = (JoinMethodHint *) JoinMethodHintCreate(
3172 leading_hint->base.hint_str,
3174 HINT_KEYWORD_LEADING);
3175 hint->base.state = HINT_STATE_USED;
3176 hint->nrels = bms_num_members(join_relids);
3177 hint->enforce_mask = ENABLE_ALL_JOIN;
3178 hint->joinrelids = bms_copy(join_relids);
3179 hint->inner_nrels = bms_num_members(inner_relids);
3180 hint->inner_joinrelids = bms_copy(inner_relids);
3182 hstate->join_hint_level[hint->nrels] =
3183 lappend(hstate->join_hint_level[hint->nrels], hint);
3187 hint->inner_nrels = bms_num_members(inner_relids);
3188 hint->inner_joinrelids = bms_copy(inner_relids);
3195 create_bms_of_relids(Hint *base, PlannerInfo *root, List *initial_rels,
3196 int nrels, char **relnames)
3199 Relids relids = NULL;
3203 for (j = 0; j < nrels; j++)
3205 relname = relnames[j];
3207 relid = find_relid_aliasname(root, relname, initial_rels,
3211 base->state = HINT_STATE_ERROR;
3214 * the aliasname is not found(relid == 0) or same aliasname was used
3215 * multiple times in a query(relid == -1)
3222 if (bms_is_member(relid, relids))
3224 hint_ereport(base->hint_str,
3225 ("Relation name \"%s\" is duplicated.", relname));
3226 base->state = HINT_STATE_ERROR;
3230 relids = bms_add_member(relids, relid);
3235 * Transform join method hint into handy form.
3237 * - create bitmap of relids from alias names, to make it easier to check
3238 * whether a join path matches a join method hint.
3239 * - add join method hints which are necessary to enforce join order
3240 * specified by Leading hint
3243 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
3244 List *initial_rels, JoinMethodHint **join_method_hints)
3252 LeadingHint *lhint = NULL;
3255 * Create bitmap of relids from alias names for each join method hint.
3256 * Bitmaps are more handy than strings in join searching.
3258 for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
3260 JoinMethodHint *hint = hstate->join_hints[i];
3262 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3265 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3266 initial_rels, hint->nrels, hint->relnames);
3268 if (hint->joinrelids == NULL || hint->base.state == HINT_STATE_ERROR)
3271 hstate->join_hint_level[hint->nrels] =
3272 lappend(hstate->join_hint_level[hint->nrels], hint);
3276 * Create bitmap of relids from alias names for each rows hint.
3277 * Bitmaps are more handy than strings in join searching.
3279 for (i = 0; i < hstate->num_hints[HINT_TYPE_ROWS]; i++)
3281 RowsHint *hint = hstate->rows_hints[i];
3283 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
3286 hint->joinrelids = create_bms_of_relids(&(hint->base), root,
3287 initial_rels, hint->nrels, hint->relnames);
3290 /* Do nothing if no Leading hint was supplied. */
3291 if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
3295 * Decide to use Leading hint。
3297 for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
3299 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
3302 if (leading_hint->base.state == HINT_STATE_ERROR)
3308 foreach(l, leading_hint->relations)
3310 relname = (char *)lfirst(l);;
3312 relid = find_relid_aliasname(root, relname, initial_rels,
3313 leading_hint->base.hint_str);
3315 leading_hint->base.state = HINT_STATE_ERROR;
3320 if (bms_is_member(relid, relids))
3322 hint_ereport(leading_hint->base.hint_str,
3323 ("Relation name \"%s\" is duplicated.", relname));
3324 leading_hint->base.state = HINT_STATE_ERROR;
3328 relids = bms_add_member(relids, relid);
3331 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3336 hint_ereport(lhint->base.hint_str,
3337 ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3338 lhint->base.state = HINT_STATE_DUPLICATION;
3340 leading_hint->base.state = HINT_STATE_USED;
3341 lhint = leading_hint;
3344 /* check to exist Leading hint marked with 'used'. */
3349 * We need join method hints which fit specified join order in every join
3350 * level. For example, Leading(A B C) virtually requires following join
3351 * method hints, if no join method hint supplied:
3353 * - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3354 * - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3356 * If we already have join method hint which fits specified join order in
3357 * that join level, we leave it as-is and don't add new hints.
3361 if (lhint->outer_inner == NULL)
3363 foreach(l, lhint->relations)
3365 JoinMethodHint *hint;
3367 relname = (char *)lfirst(l);
3370 * Find relid of the relation which has given name. If we have the
3371 * name given in Leading hint multiple times in the join, nothing to
3374 relid = find_relid_aliasname(root, relname, initial_rels,
3377 /* Create bitmap of relids for current join level. */
3378 joinrelids = bms_add_member(joinrelids, relid);
3381 /* We never have join method hint for single relation. */
3386 * If we don't have join method hint, create new one for the
3387 * join combination with all join methods are enabled.
3389 hint = find_join_hint(joinrelids);
3393 * Here relnames is not set, since Relids bitmap is sufficient
3394 * to control paths of this query afterward.
3396 hint = (JoinMethodHint *) JoinMethodHintCreate(
3397 lhint->base.hint_str,
3399 HINT_KEYWORD_LEADING);
3400 hint->base.state = HINT_STATE_USED;
3401 hint->nrels = njoinrels;
3402 hint->enforce_mask = ENABLE_ALL_JOIN;
3403 hint->joinrelids = bms_copy(joinrelids);
3406 join_method_hints[njoinrels] = hint;
3408 if (njoinrels >= nbaserel)
3411 bms_free(joinrelids);
3417 * Delete all join hints which have different combination from Leading
3420 for (i = 2; i <= njoinrels; i++)
3422 list_free(hstate->join_hint_level[i]);
3424 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3429 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3436 njoinrels = bms_num_members(joinrelids);
3437 Assert(njoinrels >= 2);
3440 * Delete all join hints which have different combination from Leading
3443 for (i = 2;i <= njoinrels; i++)
3445 if (hstate->join_hint_level[i] != NIL)
3447 ListCell *prev = NULL;
3448 ListCell *next = NULL;
3449 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3452 JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3456 if (hint->inner_nrels == 0 &&
3457 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3458 bms_equal(bms_union(hint->joinrelids, joinrelids),
3461 hstate->join_hint_level[i] =
3462 list_delete_cell(hstate->join_hint_level[i], l,
3471 bms_free(joinrelids);
3474 if (hint_state_enabled(lhint))
3476 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3483 * set_plain_rel_pathlist
3484 * Build access paths for a plain relation (no subquery, no inheritance)
3486 * This function was copied and edited from set_plain_rel_pathlist() in
3487 * src/backend/optimizer/path/allpaths.c
3490 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3492 /* Consider sequential scan */
3493 add_path(rel, create_seqscan_path(root, rel, NULL));
3495 /* Consider index scans */
3496 create_index_paths(root, rel);
3498 /* Consider TID scans */
3499 create_tidscan_paths(root, rel);
3501 /* Now find the cheapest of the paths for this rel */
3506 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3511 foreach(l, initial_rels)
3513 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3515 ScanMethodHint *hint;
3517 /* Skip relations which we can't choose scan method. */
3518 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3521 rte = root->simple_rte_array[rel->relid];
3523 /* We can't force scan method of foreign tables */
3524 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3528 * Create scan paths with GUC parameters which are at the beginning of
3529 * planner if scan method hint is not specified, otherwise use
3530 * specified hints and mark the hint as used.
3532 if ((hint = find_scan_hint(root, rel)) == NULL)
3533 set_scan_config_options(hstate->init_scan_mask,
3537 set_scan_config_options(hint->enforce_mask, hstate->context);
3538 hint->base.state = HINT_STATE_USED;
3541 list_free_deep(rel->pathlist);
3542 rel->pathlist = NIL;
3545 /* It's an "append relation", process accordingly */
3546 set_append_rel_pathlist(root, rel, rel->relid, rte);
3550 set_plain_rel_pathlist(root, rel, rte);
3555 * Restore the GUC variables we set above.
3557 set_scan_config_options(hstate->init_scan_mask, hstate->context);
3561 * wrapper of make_join_rel()
3563 * call make_join_rel() after changing enable_* parameters according to given
3567 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3570 JoinMethodHint *hint;
3574 joinrelids = bms_union(rel1->relids, rel2->relids);
3575 hint = find_join_hint(joinrelids);
3576 bms_free(joinrelids);
3579 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3581 if (hint->inner_nrels == 0)
3583 save_nestlevel = NewGUCNestLevel();
3585 set_join_config_options(hint->enforce_mask, current_hint->context);
3587 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3588 hint->base.state = HINT_STATE_USED;
3591 * Restore the GUC variables we set above.
3593 AtEOXact_GUC(true, save_nestlevel);
3596 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3605 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3606 RelOptInfo *joinrel,
3607 RelOptInfo *outerrel,
3608 RelOptInfo *innerrel,
3610 SpecialJoinInfo *sjinfo,
3613 ScanMethodHint *scan_hint = NULL;
3615 JoinMethodHint *join_hint;
3618 if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3620 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3621 scan_hint->base.state = HINT_STATE_USED;
3624 joinrelids = bms_union(outerrel->relids, innerrel->relids);
3625 join_hint = find_join_hint(joinrelids);
3626 bms_free(joinrelids);
3628 if (join_hint && join_hint->inner_nrels != 0)
3630 save_nestlevel = NewGUCNestLevel();
3632 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3635 set_join_config_options(join_hint->enforce_mask,
3636 current_hint->context);
3638 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3639 sjinfo, restrictlist);
3640 join_hint->base.state = HINT_STATE_USED;
3644 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3645 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3646 sjinfo, restrictlist);
3650 * Restore the GUC variables we set above.
3652 AtEOXact_GUC(true, save_nestlevel);
3655 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3656 sjinfo, restrictlist);
3658 if (scan_hint != NULL)
3659 set_scan_config_options(current_hint->init_scan_mask,
3660 current_hint->context);
3664 get_num_baserels(List *initial_rels)
3669 foreach(l, initial_rels)
3671 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3673 if (rel->reloptkind == RELOPT_BASEREL)
3675 else if (rel->reloptkind ==RELOPT_JOINREL)
3676 nbaserel+= bms_num_members(rel->relids);
3679 /* other values not expected here */
3680 elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3688 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3691 JoinMethodHint **join_method_hints;
3695 bool leading_hint_enable;
3698 * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3699 * valid hint is supplied or current nesting depth is nesting depth of SPI
3702 if (!current_hint || nested_level > 0)
3704 if (prev_join_search)
3705 return (*prev_join_search) (root, levels_needed, initial_rels);
3706 else if (enable_geqo && levels_needed >= geqo_threshold)
3707 return geqo(root, levels_needed, initial_rels);
3709 return standard_join_search(root, levels_needed, initial_rels);
3712 /* We apply scan method hint rebuild scan path. */
3713 rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3716 * In the case using GEQO, only scan method hints and Set hints have
3717 * effect. Join method and join order is not controllable by hints.
3719 if (enable_geqo && levels_needed >= geqo_threshold)
3720 return geqo(root, levels_needed, initial_rels);
3722 nbaserel = get_num_baserels(initial_rels);
3723 current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3724 join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3726 leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3727 initial_rels, join_method_hints);
3729 rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3731 for (i = 2; i <= nbaserel; i++)
3733 list_free(current_hint->join_hint_level[i]);
3735 /* free Leading hint only */
3736 if (join_method_hints[i] != NULL &&
3737 join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3738 JoinMethodHintDelete(join_method_hints[i]);
3740 pfree(current_hint->join_hint_level);
3741 pfree(join_method_hints);
3743 if (leading_hint_enable)
3744 set_join_config_options(current_hint->init_join_mask,
3745 current_hint->context);
3752 * Build access paths for a base relation
3754 * This function was copied and edited from set_rel_pathlist() in
3755 * src/backend/optimizer/path/allpaths.c
3758 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3759 Index rti, RangeTblEntry *rte)
3761 if (IS_DUMMY_REL(rel))
3763 /* We already proved the relation empty, so nothing more to do */
3767 /* It's an "append relation", process accordingly */
3768 set_append_rel_pathlist(root, rel, rti, rte);
3772 if (rel->rtekind == RTE_RELATION)
3774 if (rte->relkind == RELKIND_RELATION)
3776 /* Plain relation */
3777 set_plain_rel_pathlist(root, rel, rte);
3780 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3783 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3788 * stmt_beg callback is called when each query in PL/pgSQL function is about
3789 * to be executed. At that timing, we save query string in the global variable
3790 * plpgsql_query_string to use it in planner hook. It's safe to use one global
3791 * variable for the purpose, because its content is only necessary until
3792 * planner hook is called for the query, so recursive PL/pgSQL function calls
3793 * don't harm this mechanism.
3796 pg_hint_plan_plpgsql_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3798 PLpgSQL_expr *expr = NULL;
3800 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
3802 case PLPGSQL_STMT_FORS:
3803 expr = ((PLpgSQL_stmt_fors *) stmt)->query;
3805 case PLPGSQL_STMT_FORC:
3806 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_forc *)stmt)->curvar]))->cursor_explicit_expr;
3808 case PLPGSQL_STMT_RETURN_QUERY:
3809 if (((PLpgSQL_stmt_return_query *) stmt)->query != NULL)
3810 expr = ((PLpgSQL_stmt_return_query *) stmt)->query;
3812 expr = ((PLpgSQL_stmt_return_query *) stmt)->dynquery;
3814 case PLPGSQL_STMT_EXECSQL:
3815 expr = ((PLpgSQL_stmt_execsql *) stmt)->sqlstmt;
3817 case PLPGSQL_STMT_DYNEXECUTE:
3818 expr = ((PLpgSQL_stmt_dynexecute *) stmt)->query;
3820 case PLPGSQL_STMT_DYNFORS:
3821 expr = ((PLpgSQL_stmt_dynfors *) stmt)->query;
3823 case PLPGSQL_STMT_OPEN:
3824 if (((PLpgSQL_stmt_open *) stmt)->query != NULL)
3825 expr = ((PLpgSQL_stmt_open *) stmt)->query;
3826 else if (((PLpgSQL_stmt_open *) stmt)->dynquery != NULL)
3827 expr = ((PLpgSQL_stmt_open *) stmt)->dynquery;
3829 expr = ((PLpgSQL_var *) (estate->datums[((PLpgSQL_stmt_open *)stmt)->curvar]))->cursor_explicit_expr;
3836 plpgsql_query_string = expr->query;
3840 * stmt_end callback is called then each query in PL/pgSQL function has
3841 * finished. At that timing, we clear plpgsql_query_string to tell planner
3842 * hook that next call is not for a query written in PL/pgSQL block.
3845 pg_hint_plan_plpgsql_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
3847 if ((enum PLpgSQL_stmt_types) stmt->cmd_type == PLPGSQL_STMT_EXECSQL)
3848 plpgsql_query_string = NULL;
3851 #define standard_join_search pg_hint_plan_standard_join_search
3852 #define join_search_one_level pg_hint_plan_join_search_one_level
3853 #define make_join_rel make_join_rel_wrapper
3856 #undef make_join_rel
3857 #define make_join_rel pg_hint_plan_make_join_rel
3858 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3859 #include "make_join_rel.c"
3861 #include "pg_stat_statements.c"