OSDN Git Service

開き括弧も要引用符文字とした。
[pghintplan/pg_hint_plan.git] / pg_hint_plan.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_hint_plan.c
4  *                do instructions or hints to the planner using C-style block comments
5  *                of the SQL.
6  *
7  * Copyright (c) 2012, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8  *
9  *-------------------------------------------------------------------------
10  */
11 #include "postgres.h"
12 #include "commands/prepare.h"
13 #include "mb/pg_wchar.h"
14 #include "miscadmin.h"
15 #include "nodes/nodeFuncs.h"
16 #include "optimizer/clauses.h"
17 #include "optimizer/cost.h"
18 #include "optimizer/geqo.h"
19 #include "optimizer/joininfo.h"
20 #include "optimizer/pathnode.h"
21 #include "optimizer/paths.h"
22 #include "optimizer/plancat.h"
23 #include "optimizer/planner.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/restrictinfo.h"
26 #include "parser/scansup.h"
27 #include "tcop/utility.h"
28 #include "utils/lsyscache.h"
29 #include "utils/memutils.h"
30 #if PG_VERSION_NUM >= 90200
31 #include "catalog/pg_class.h"
32 #endif
33
34 #ifdef PG_MODULE_MAGIC
35 PG_MODULE_MAGIC;
36 #endif
37
38 #if PG_VERSION_NUM < 90100
39 #error unsupported PostgreSQL version
40 #endif
41
42 #define BLOCK_COMMENT_START             "/*"
43 #define BLOCK_COMMENT_END               "*/"
44 #define HINT_COMMENT_KEYWORD    "+"
45 #define HINT_START                              BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
46 #define HINT_END                                BLOCK_COMMENT_END
47
48 /* hint keywords */
49 #define HINT_SEQSCAN                    "SeqScan"
50 #define HINT_INDEXSCAN                  "IndexScan"
51 #define HINT_BITMAPSCAN                 "BitmapScan"
52 #define HINT_TIDSCAN                    "TidScan"
53 #define HINT_NOSEQSCAN                  "NoSeqScan"
54 #define HINT_NOINDEXSCAN                "NoIndexScan"
55 #define HINT_NOBITMAPSCAN               "NoBitmapScan"
56 #define HINT_NOTIDSCAN                  "NoTidScan"
57 #if PG_VERSION_NUM >= 90200
58 #define HINT_INDEXONLYSCAN              "IndexOnlyScan"
59 #define HINT_NOINDEXONLYSCAN    "NoIndexOnlyScan"
60 #endif
61 #define HINT_NESTLOOP                   "NestLoop"
62 #define HINT_MERGEJOIN                  "MergeJoin"
63 #define HINT_HASHJOIN                   "HashJoin"
64 #define HINT_NONESTLOOP                 "NoNestLoop"
65 #define HINT_NOMERGEJOIN                "NoMergeJoin"
66 #define HINT_NOHASHJOIN                 "NoHashJoin"
67 #define HINT_LEADING                    "Leading"
68 #define HINT_SET                                "Set"
69
70 #define HINT_ARRAY_DEFAULT_INITSIZE 8
71
72 #define hint_ereport(str, detail) \
73         ereport(pg_hint_plan_parse_messages, \
74                         (errmsg("hint syntax error at or near \"%s\"", (str)), \
75                          errdetail detail))
76
77 #define skip_space(str) \
78         while (isspace(*str)) \
79                 str++;
80
81 enum
82 {
83         ENABLE_SEQSCAN = 0x01,
84         ENABLE_INDEXSCAN = 0x02,
85         ENABLE_BITMAPSCAN = 0x04,
86         ENABLE_TIDSCAN = 0x08,
87 #if PG_VERSION_NUM >= 90200
88         ENABLE_INDEXONLYSCAN = 0x10
89 #endif
90 } SCAN_TYPE_BITS;
91
92 enum
93 {
94         ENABLE_NESTLOOP = 0x01,
95         ENABLE_MERGEJOIN = 0x02,
96         ENABLE_HASHJOIN = 0x04
97 } JOIN_TYPE_BITS;
98
99 #if PG_VERSION_NUM >= 90200
100 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
101                                                  ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
102                                                  ENABLE_INDEXONLYSCAN)
103 #else
104 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
105                                                  ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
106 #endif
107 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
108 #define DISABLE_ALL_SCAN 0
109 #define DISABLE_ALL_JOIN 0
110
111 /* hint keyword of enum type*/
112 typedef enum HintKeyword
113 {
114         HINT_KEYWORD_SEQSCAN,
115         HINT_KEYWORD_INDEXSCAN,
116         HINT_KEYWORD_BITMAPSCAN,
117         HINT_KEYWORD_TIDSCAN,
118         HINT_KEYWORD_NOSEQSCAN,
119         HINT_KEYWORD_NOINDEXSCAN,
120         HINT_KEYWORD_NOBITMAPSCAN,
121         HINT_KEYWORD_NOTIDSCAN,
122 #if PG_VERSION_NUM >= 90200
123         HINT_KEYWORD_INDEXONLYSCAN,
124         HINT_KEYWORD_NOINDEXONLYSCAN,
125 #endif
126         HINT_KEYWORD_NESTLOOP,
127         HINT_KEYWORD_MERGEJOIN,
128         HINT_KEYWORD_HASHJOIN,
129         HINT_KEYWORD_NONESTLOOP,
130         HINT_KEYWORD_NOMERGEJOIN,
131         HINT_KEYWORD_NOHASHJOIN,
132         HINT_KEYWORD_LEADING,
133         HINT_KEYWORD_SET,
134         HINT_KEYWORD_UNRECOGNIZED
135 } HintKeyword;
136
137 typedef struct Hint Hint;
138 typedef struct HintState HintState;
139
140 typedef Hint *(*HintCreateFunction) (const char *hint_str,
141                                                                          const char *keyword,
142                                                                          HintKeyword hint_keyword);
143 typedef void (*HintDeleteFunction) (Hint *hint);
144 typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
145 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
146 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
147                                                                                   Query *parse, const char *str);
148
149 /* hint types */
150 #define NUM_HINT_TYPE   4
151 typedef enum HintType
152 {
153         HINT_TYPE_SCAN_METHOD,
154         HINT_TYPE_JOIN_METHOD,
155         HINT_TYPE_LEADING,
156         HINT_TYPE_SET
157 } HintType;
158
159 static const char *HintTypeName[] = {
160         "scan method",
161         "join method",
162         "leading",
163         "set"
164 };
165
166 /* hint status */
167 typedef enum HintStatus
168 {
169         HINT_STATE_NOTUSED = 0,         /* specified relation not used in query */
170         HINT_STATE_USED,                        /* hint is used */
171         HINT_STATE_DUPLICATION,         /* specified hint duplication */
172         HINT_STATE_ERROR                        /* execute error (parse error does not include
173                                                                  * it) */
174 } HintStatus;
175
176 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
177                                                                   (hint)->base.state == HINT_STATE_USED)
178
179 /* common data for all hints. */
180 struct Hint
181 {
182         const char                 *hint_str;           /* must not do pfree */
183         const char                 *keyword;            /* must not do pfree */
184         HintKeyword                     hint_keyword;
185         HintType                        type;
186         HintStatus                      state;
187         HintDeleteFunction      delete_func;
188         HintDumpFunction        dump_func;
189         HintCmpFunction         cmp_func;
190         HintParseFunction       parse_func;
191 };
192
193 /* scan method hints */
194 typedef struct ScanMethodHint
195 {
196         Hint                    base;
197         char               *relname;
198         List               *indexnames;
199         unsigned char   enforce_mask;
200 } ScanMethodHint;
201
202 /* join method hints */
203 typedef struct JoinMethodHint
204 {
205         Hint                    base;
206         int                             nrels;
207         int                             inner_nrels;
208         char              **relnames;
209         unsigned char   enforce_mask;
210         Relids                  joinrelids;
211         Relids                  inner_joinrelids;
212 } JoinMethodHint;
213
214 /* join order hints */
215 typedef struct OuterInnerRels
216 {
217         char   *relation;
218         List   *outer_inner_pair;
219 } OuterInnerRels;
220
221 typedef struct LeadingHint
222 {
223         Hint                    base;
224         List               *relations;  /* relation names specified in Leading hint */
225         OuterInnerRels *outer_inner;
226 } LeadingHint;
227
228 /* change a run-time parameter hints */
229 typedef struct SetHint
230 {
231         Hint    base;
232         char   *name;                           /* name of variable */
233         char   *value;
234         List   *words;
235 } SetHint;
236
237 /*
238  * Describes a context of hint processing.
239  */
240 struct HintState
241 {
242         char               *hint_str;                   /* original hint string */
243
244         /* all hint */
245         int                             nall_hints;                     /* # of valid all hints */
246         int                             max_all_hints;          /* # of slots for all hints */
247         Hint              **all_hints;                  /* parsed all hints */
248
249         /* # of each hints */
250         int                             num_hints[NUM_HINT_TYPE];
251
252         /* for scan method hints */
253         ScanMethodHint **scan_hints;            /* parsed scan hints */
254         int                             init_scan_mask;         /* initial value scan parameter */
255         Index                   parent_relid;           /* inherit parent table relid */
256         ScanMethodHint *parent_hint;            /* inherit parent table scan hint */
257
258         /* for join method hints */
259         JoinMethodHint **join_hints;            /* parsed join hints */
260         int                             init_join_mask;         /* initial value join parameter */
261         List              **join_hint_level;
262
263         /* for Leading hint */
264         LeadingHint       **leading_hint;               /* parsed last specified Leading hint */
265
266         /* for Set hints */
267         SetHint           **set_hints;                  /* parsed Set hints */
268         GucContext              context;                        /* which GUC parameters can we set? */
269 };
270
271 /*
272  * Describes a hint parser module which is bound with particular hint keyword.
273  */
274 typedef struct HintParser
275 {
276         char                       *keyword;
277         HintCreateFunction      create_func;
278         HintKeyword                     hint_keyword;
279 } HintParser;
280
281 /* Module callbacks */
282 void            _PG_init(void);
283 void            _PG_fini(void);
284
285 static void push_hint(HintState *hstate);
286 static void pop_hint(void);
287
288 static void pg_hint_plan_ProcessUtility(Node *parsetree,
289                                                                                 const char *queryString,
290                                                                                 ParamListInfo params, bool isTopLevel,
291                                                                                 DestReceiver *dest,
292                                                                                 char *completionTag);
293 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
294                                                                                  ParamListInfo boundParams);
295 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
296                                                                                    Oid relationObjectId,
297                                                                                    bool inhparent, RelOptInfo *rel);
298 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
299                                                                                         int levels_needed,
300                                                                                         List *initial_rels);
301
302 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
303                                                                   HintKeyword hint_keyword);
304 static void ScanMethodHintDelete(ScanMethodHint *hint);
305 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
306 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
307 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
308                                                                            Query *parse, const char *str);
309 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
310                                                                   HintKeyword hint_keyword);
311 static void JoinMethodHintDelete(JoinMethodHint *hint);
312 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
313 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
314 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
315                                                                            Query *parse, const char *str);
316 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
317                                                            HintKeyword hint_keyword);
318 static void LeadingHintDelete(LeadingHint *hint);
319 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
320 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
321 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
322                                                                         Query *parse, const char *str);
323 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
324                                                    HintKeyword hint_keyword);
325 static void SetHintDelete(SetHint *hint);
326 static void SetHintDump(SetHint *hint, StringInfo buf);
327 static int SetHintCmp(const SetHint *a, const SetHint *b);
328 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
329                                                                 const char *str);
330
331 static void dump_quote_value(StringInfo buf, const char *value);
332
333 static const char *parse_quote_value_term_char(const char *str, char **word,
334                                                                                            bool truncate, char term_char);
335
336 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
337                                                                                           int levels_needed,
338                                                                                           List *initial_rels);
339 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
340 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
341                                                                           ListCell *other_rels);
342 static void make_rels_by_clauseless_joins(PlannerInfo *root,
343                                                                                   RelOptInfo *old_rel,
344                                                                                   ListCell *other_rels);
345 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
346 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
347                                                                         Index rti, RangeTblEntry *rte);
348 #if PG_VERSION_NUM >= 90200
349 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
350                                                    List *live_childrels,
351                                                    List *all_child_pathkeys);
352 #endif
353 static List *accumulate_append_subpath(List *subpaths, Path *path);
354 #if PG_VERSION_NUM < 90200
355 static void set_dummy_rel_pathlist(RelOptInfo *rel);
356 #endif
357 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
358                                                                            RelOptInfo *rel2);
359
360 /* GUC variables */
361 static bool     pg_hint_plan_enable_hint = true;
362 static bool     pg_hint_plan_debug_print = false;
363 static int      pg_hint_plan_parse_messages = INFO;
364
365 static const struct config_enum_entry parse_messages_level_options[] = {
366         {"debug", DEBUG2, true},
367         {"debug5", DEBUG5, false},
368         {"debug4", DEBUG4, false},
369         {"debug3", DEBUG3, false},
370         {"debug2", DEBUG2, false},
371         {"debug1", DEBUG1, false},
372         {"log", LOG, false},
373         {"info", INFO, false},
374         {"notice", NOTICE, false},
375         {"warning", WARNING, false},
376         {"error", ERROR, false},
377         /*
378          * {"fatal", FATAL, true},
379          * {"panic", PANIC, true},
380          */
381         {NULL, 0, false}
382 };
383
384 /* Saved hook values in case of unload */
385 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
386 static planner_hook_type prev_planner = NULL;
387 static get_relation_info_hook_type prev_get_relation_info = NULL;
388 static join_search_hook_type prev_join_search = NULL;
389
390 /* Hold reference to currently active hint */
391 static HintState *current_hint = NULL;
392
393 /*
394  * List of hint contexts.  We treat the head of the list as the Top of the
395  * context stack, so current_hint always points the first element of this list.
396  */
397 static List *HintStateStack = NIL;
398
399 /*
400  * Holds statement name during executing EXECUTE command.  NULL for other
401  * statements.
402  */
403 static char        *stmt_name = NULL;
404
405 static const HintParser parsers[] = {
406         {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
407         {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
408         {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
409         {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
410         {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
411         {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
412         {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
413         {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
414 #if PG_VERSION_NUM >= 90200
415         {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
416         {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
417 #endif
418         {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
419         {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
420         {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
421         {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
422         {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
423         {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
424         {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
425         {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
426         {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
427 };
428
429 /*
430  * Module load callbacks
431  */
432 void
433 _PG_init(void)
434 {
435         /* Define custom GUC variables. */
436         DefineCustomBoolVariable("pg_hint_plan.enable_hint",
437                          "Force planner to use plans specified in the hint comment preceding to the query.",
438                                                          NULL,
439                                                          &pg_hint_plan_enable_hint,
440                                                          true,
441                                                          PGC_USERSET,
442                                                          0,
443                                                          NULL,
444                                                          NULL,
445                                                          NULL);
446
447         DefineCustomBoolVariable("pg_hint_plan.debug_print",
448                                                          "Logs results of hint parsing.",
449                                                          NULL,
450                                                          &pg_hint_plan_debug_print,
451                                                          false,
452                                                          PGC_USERSET,
453                                                          0,
454                                                          NULL,
455                                                          NULL,
456                                                          NULL);
457
458         DefineCustomEnumVariable("pg_hint_plan.parse_messages",
459                                                          "Message level of parse errors.",
460                                                          NULL,
461                                                          &pg_hint_plan_parse_messages,
462                                                          INFO,
463                                                          parse_messages_level_options,
464                                                          PGC_USERSET,
465                                                          0,
466                                                          NULL,
467                                                          NULL,
468                                                          NULL);
469
470         /* Install hooks. */
471         prev_ProcessUtility = ProcessUtility_hook;
472         ProcessUtility_hook = pg_hint_plan_ProcessUtility;
473         prev_planner = planner_hook;
474         planner_hook = pg_hint_plan_planner;
475         prev_get_relation_info = get_relation_info_hook;
476         get_relation_info_hook = pg_hint_plan_get_relation_info;
477         prev_join_search = join_search_hook;
478         join_search_hook = pg_hint_plan_join_search;
479 }
480
481 /*
482  * Module unload callback
483  * XXX never called
484  */
485 void
486 _PG_fini(void)
487 {
488         /* Uninstall hooks. */
489         ProcessUtility_hook = prev_ProcessUtility;
490         planner_hook = prev_planner;
491         get_relation_info_hook = prev_get_relation_info;
492         join_search_hook = prev_join_search;
493 }
494
495 /*
496  * create and delete functions the hint object
497  */
498
499 static Hint *
500 ScanMethodHintCreate(const char *hint_str, const char *keyword,
501                                          HintKeyword hint_keyword)
502 {
503         ScanMethodHint *hint;
504
505         hint = palloc(sizeof(ScanMethodHint));
506         hint->base.hint_str = hint_str;
507         hint->base.keyword = keyword;
508         hint->base.hint_keyword = hint_keyword;
509         hint->base.type = HINT_TYPE_SCAN_METHOD;
510         hint->base.state = HINT_STATE_NOTUSED;
511         hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
512         hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
513         hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
514         hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
515         hint->relname = NULL;
516         hint->indexnames = NIL;
517         hint->enforce_mask = 0;
518
519         return (Hint *) hint;
520 }
521
522 static void
523 ScanMethodHintDelete(ScanMethodHint *hint)
524 {
525         if (!hint)
526                 return;
527
528         if (hint->relname)
529                 pfree(hint->relname);
530         list_free_deep(hint->indexnames);
531         pfree(hint);
532 }
533
534 static Hint *
535 JoinMethodHintCreate(const char *hint_str, const char *keyword,
536                                          HintKeyword hint_keyword)
537 {
538         JoinMethodHint *hint;
539
540         hint = palloc(sizeof(JoinMethodHint));
541         hint->base.hint_str = hint_str;
542         hint->base.keyword = keyword;
543         hint->base.hint_keyword = hint_keyword;
544         hint->base.type = HINT_TYPE_JOIN_METHOD;
545         hint->base.state = HINT_STATE_NOTUSED;
546         hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
547         hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
548         hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
549         hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
550         hint->nrels = 0;
551         hint->inner_nrels = 0;
552         hint->relnames = NULL;
553         hint->enforce_mask = 0;
554         hint->joinrelids = NULL;
555         hint->inner_joinrelids = NULL;
556
557         return (Hint *) hint;
558 }
559
560 static void
561 JoinMethodHintDelete(JoinMethodHint *hint)
562 {
563         if (!hint)
564                 return;
565
566         if (hint->relnames)
567         {
568                 int     i;
569
570                 for (i = 0; i < hint->nrels; i++)
571                         pfree(hint->relnames[i]);
572                 pfree(hint->relnames);
573         }
574
575         bms_free(hint->joinrelids);
576         bms_free(hint->inner_joinrelids);
577         pfree(hint);
578 }
579
580 static Hint *
581 LeadingHintCreate(const char *hint_str, const char *keyword,
582                                   HintKeyword hint_keyword)
583 {
584         LeadingHint        *hint;
585
586         hint = palloc(sizeof(LeadingHint));
587         hint->base.hint_str = hint_str;
588         hint->base.keyword = keyword;
589         hint->base.hint_keyword = hint_keyword;
590         hint->base.type = HINT_TYPE_LEADING;
591         hint->base.state = HINT_STATE_NOTUSED;
592         hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
593         hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
594         hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
595         hint->base.parse_func = (HintParseFunction) LeadingHintParse;
596         hint->relations = NIL;
597         hint->outer_inner = NULL;
598
599         return (Hint *) hint;
600 }
601
602 static void
603 LeadingHintDelete(LeadingHint *hint)
604 {
605         if (!hint)
606                 return;
607
608         list_free_deep(hint->relations);
609         free(hint->outer_inner);
610         pfree(hint);
611 }
612
613 static Hint *
614 SetHintCreate(const char *hint_str, const char *keyword,
615                           HintKeyword hint_keyword)
616 {
617         SetHint    *hint;
618
619         hint = palloc(sizeof(SetHint));
620         hint->base.hint_str = hint_str;
621         hint->base.keyword = keyword;
622         hint->base.hint_keyword = hint_keyword;
623         hint->base.type = HINT_TYPE_SET;
624         hint->base.state = HINT_STATE_NOTUSED;
625         hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
626         hint->base.dump_func = (HintDumpFunction) SetHintDump;
627         hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
628         hint->base.parse_func = (HintParseFunction) SetHintParse;
629         hint->name = NULL;
630         hint->value = NULL;
631         hint->words = NIL;
632
633         return (Hint *) hint;
634 }
635
636 static void
637 SetHintDelete(SetHint *hint)
638 {
639         if (!hint)
640                 return;
641
642         if (hint->name)
643                 pfree(hint->name);
644         if (hint->value)
645                 pfree(hint->value);
646         if (hint->words)
647                 list_free(hint->words);
648         pfree(hint);
649 }
650
651 static HintState *
652 HintStateCreate(void)
653 {
654         HintState   *hstate;
655
656         hstate = palloc(sizeof(HintState));
657         hstate->hint_str = NULL;
658         hstate->nall_hints = 0;
659         hstate->max_all_hints = 0;
660         hstate->all_hints = NULL;
661         memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
662         hstate->scan_hints = NULL;
663         hstate->init_scan_mask = 0;
664         hstate->parent_relid = 0;
665         hstate->parent_hint = NULL;
666         hstate->join_hints = NULL;
667         hstate->init_join_mask = 0;
668         hstate->join_hint_level = NULL;
669         hstate->leading_hint = NULL;
670         hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
671         hstate->set_hints = NULL;
672
673         return hstate;
674 }
675
676 static void
677 HintStateDelete(HintState *hstate)
678 {
679         int                     i;
680
681         if (!hstate)
682                 return;
683
684         if (hstate->hint_str)
685                 pfree(hstate->hint_str);
686
687         for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
688                 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
689         if (hstate->all_hints)
690                 pfree(hstate->all_hints);
691 }
692
693 /*
694  * dump functions
695  */
696
697 /*
698  * Quote value as needed and dump it to buf.
699  */
700 static void
701 dump_quote_value(StringInfo buf, const char *value)
702 {
703         bool            need_quote = false;
704         const char *str;
705
706         for (str = value; *str != '\0'; str++)
707         {
708                 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
709                 {
710                         need_quote = true;
711                         appendStringInfoCharMacro(buf, '"');
712                         break;
713                 }
714         }
715
716         for (str = value; *str != '\0'; str++)
717         {
718                 if (*str == '"')
719                         appendStringInfoCharMacro(buf, '"');
720
721                 appendStringInfoCharMacro(buf, *str);
722         }
723
724         if (need_quote)
725                 appendStringInfoCharMacro(buf, '"');
726 }
727
728 static void
729 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
730 {
731         ListCell   *l;
732
733         appendStringInfo(buf, "%s(", hint->base.keyword);
734         if (hint->relname != NULL)
735         {
736                 dump_quote_value(buf, hint->relname);
737                 foreach(l, hint->indexnames)
738                 {
739                         appendStringInfoCharMacro(buf, ' ');
740                         dump_quote_value(buf, (char *) lfirst(l));
741                 }
742         }
743         appendStringInfoString(buf, ")\n");
744 }
745
746 static void
747 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
748 {
749         int     i;
750
751         appendStringInfo(buf, "%s(", hint->base.keyword);
752         if (hint->relnames != NULL)
753         {
754                 dump_quote_value(buf, hint->relnames[0]);
755                 for (i = 1; i < hint->nrels; i++)
756                 {
757                         appendStringInfoCharMacro(buf, ' ');
758                         dump_quote_value(buf, hint->relnames[i]);
759                 }
760         }
761         appendStringInfoString(buf, ")\n");
762
763 }
764
765 static void
766 OuterInnerDump(OuterInnerRels *outer_inner, StringInfo buf)
767 {
768         if (outer_inner->relation == NULL)
769         {
770                 bool            is_first;
771                 ListCell   *l;
772
773                 is_first = true;
774
775                 appendStringInfoCharMacro(buf, '(');
776                 foreach(l, outer_inner->outer_inner_pair)
777                 {
778                         if (is_first)
779                                 is_first = false;
780                         else
781                                 appendStringInfoCharMacro(buf, ' ');
782
783                         OuterInnerDump(lfirst(l), buf);
784                 }
785
786                 appendStringInfoCharMacro(buf, ')');
787         }
788         else
789                 dump_quote_value(buf, outer_inner->relation);
790 }
791
792 static void
793 LeadingHintDump(LeadingHint *hint, StringInfo buf)
794 {
795         bool            is_first;
796         ListCell   *l;
797
798         appendStringInfo(buf, "%s(", HINT_LEADING);
799         is_first = true;
800         if (hint->outer_inner == NULL)
801         {
802                 foreach(l, hint->relations)
803                 {
804                         if (is_first)
805                                 is_first = false;
806                         else
807                                 appendStringInfoCharMacro(buf, ' ');
808
809                         dump_quote_value(buf, (char *) lfirst(l));
810                 }
811         }
812         else
813                 OuterInnerDump(hint->outer_inner, buf);
814
815         appendStringInfoString(buf, ")\n");
816 }
817
818 static void
819 SetHintDump(SetHint *hint, StringInfo buf)
820 {
821         bool            is_first = true;
822         ListCell   *l;
823
824         appendStringInfo(buf, "%s(", HINT_SET);
825         foreach(l, hint->words)
826         {
827                 if (is_first)
828                         is_first = false;
829                 else
830                         appendStringInfoCharMacro(buf, ' ');
831
832                 dump_quote_value(buf, (char *) lfirst(l));
833         }
834         appendStringInfo(buf, ")\n");
835 }
836
837 static void
838 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
839                           HintStatus state)
840 {
841         int     i;
842
843         appendStringInfo(buf, "%s:\n", title);
844         for (i = 0; i < hstate->nall_hints; i++)
845         {
846                 if (hstate->all_hints[i]->state != state)
847                         continue;
848
849                 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
850         }
851 }
852
853 static void
854 HintStateDump(HintState *hstate)
855 {
856         StringInfoData  buf;
857
858         if (!hstate)
859         {
860                 elog(LOG, "pg_hint_plan:\nno hint");
861                 return;
862         }
863
864         initStringInfo(&buf);
865
866         appendStringInfoString(&buf, "pg_hint_plan:\n");
867         all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
868         all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
869         all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
870         all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
871
872         elog(LOG, "%s", buf.data);
873
874         pfree(buf.data);
875 }
876
877 /*
878  * compare functions
879  */
880
881 static int
882 RelnameCmp(const void *a, const void *b)
883 {
884         const char *relnamea = *((const char **) a);
885         const char *relnameb = *((const char **) b);
886
887         return strcmp(relnamea, relnameb);
888 }
889
890 static int
891 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
892 {
893         return RelnameCmp(&a->relname, &b->relname);
894 }
895
896 static int
897 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
898 {
899         int     i;
900
901         if (a->nrels != b->nrels)
902                 return a->nrels - b->nrels;
903
904         for (i = 0; i < a->nrels; i++)
905         {
906                 int     result;
907                 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
908                         return result;
909         }
910
911         return 0;
912 }
913
914 static int
915 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
916 {
917         return 0;
918 }
919
920 static int
921 SetHintCmp(const SetHint *a, const SetHint *b)
922 {
923         return strcmp(a->name, b->name);
924 }
925
926 static int
927 HintCmp(const void *a, const void *b)
928 {
929         const Hint *hinta = *((const Hint **) a);
930         const Hint *hintb = *((const Hint **) b);
931
932         if (hinta->type != hintb->type)
933                 return hinta->type - hintb->type;
934         if (hinta->state == HINT_STATE_ERROR)
935                 return -1;
936         if (hintb->state == HINT_STATE_ERROR)
937                 return 1;
938         return hinta->cmp_func(hinta, hintb);
939 }
940
941 /*
942  * Returns byte offset of hint b from hint a.  If hint a was specified before
943  * b, positive value is returned.
944  */
945 static int
946 HintCmpWithPos(const void *a, const void *b)
947 {
948         const Hint *hinta = *((const Hint **) a);
949         const Hint *hintb = *((const Hint **) b);
950         int             result;
951
952         result = HintCmp(a, b);
953         if (result == 0)
954                 result = hinta->hint_str - hintb->hint_str;
955
956         return result;
957 }
958
959 /*
960  * parse functions
961  */
962 static const char *
963 parse_keyword(const char *str, StringInfo buf)
964 {
965         skip_space(str);
966
967         while (!isspace(*str) && *str != '(' && *str != '\0')
968                 appendStringInfoCharMacro(buf, *str++);
969
970         return str;
971 }
972
973 static const char *
974 skip_parenthesis(const char *str, char parenthesis)
975 {
976         skip_space(str);
977
978         if (*str != parenthesis)
979         {
980                 if (parenthesis == '(')
981                         hint_ereport(str, ("Opening parenthesis is necessary."));
982                 else if (parenthesis == ')')
983                         hint_ereport(str, ("Closing parenthesis is necessary."));
984
985                 return NULL;
986         }
987
988         str++;
989
990         return str;
991 }
992
993 /*
994  * Parse a token from str, and store malloc'd copy into word.  A token can be
995  * quoted with '"'.  Return value is pointer to unparsed portion of original
996  * string, or NULL if an error occurred.
997  *
998  * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
999  */
1000 static const char *
1001 parse_quote_value(const char *str, char **word, bool truncate)
1002 {
1003         return parse_quote_value_term_char(str, word, truncate, '\0');
1004 }
1005
1006 /*
1007  * In term_char, We specified the special character which a terminal of a word.
1008  * When we do not have a special character, We specified '\0'.
1009  */
1010 static const char *
1011 parse_quote_value_term_char(const char *str, char **word, bool truncate,
1012                                                         char term_char)
1013 {
1014         StringInfoData  buf;
1015         bool                    in_quote;
1016
1017         /* Skip leading spaces. */
1018         skip_space(str);
1019
1020         initStringInfo(&buf);
1021         if (*str == '"')
1022         {
1023                 str++;
1024                 in_quote = true;
1025         }
1026         else
1027                 in_quote = false;
1028
1029         while (true)
1030         {
1031                 if (in_quote)
1032                 {
1033                         /* Double quotation must be closed. */
1034                         if (*str == '\0')
1035                         {
1036                                 pfree(buf.data);
1037                                 hint_ereport(str, ("Unterminated quoted string."));
1038                                 return NULL;
1039                         }
1040
1041                         /*
1042                          * Skip escaped double quotation.
1043                          *
1044                          * We don't allow slash-asterisk and asterisk-slash (delimiters of
1045                          * block comments) to be an object name, so users must specify
1046                          * alias for such object names.
1047                          *
1048                          * Those special names can be allowed if we care escaped slashes
1049                          * and asterisks, but we don't.
1050                          */
1051                         if (*str == '"')
1052                         {
1053                                 str++;
1054                                 if (*str != '"')
1055                                         break;
1056                         }
1057                 }
1058                 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0' ||
1059                                  *str == term_char)
1060                         break;
1061
1062                 appendStringInfoCharMacro(&buf, *str++);
1063         }
1064
1065         if (buf.len == 0)
1066         {
1067                 hint_ereport(str, ("Zero-length delimited string."));
1068
1069                 pfree(buf.data);
1070
1071                 return NULL;
1072         }
1073
1074         /* Truncate name if it's too long */
1075         if (truncate)
1076                 truncate_identifier(buf.data, strlen(buf.data), true);
1077
1078         *word = buf.data;
1079
1080         return str;
1081 }
1082
1083 static OuterInnerRels *
1084 OuterInnerRelsCreate(OuterInnerRels *outer_inner, char *name, List *outer_inner_list)
1085 {
1086         outer_inner = palloc(sizeof(OuterInnerRels));
1087         outer_inner->relation = name;
1088         outer_inner->outer_inner_pair = outer_inner_list;
1089
1090         return outer_inner;
1091 }
1092
1093 static const char *
1094 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1095 {
1096         char   *name;
1097         bool    truncate = true;
1098
1099         OuterInnerRels *outer_inner_rels;
1100         outer_inner_rels = NULL;
1101
1102         skip_space(str);
1103
1104         /* Store words in parentheses into outer_inner_list. */
1105         while(*str != ')' && *str != '\0')
1106         {
1107                 if (*str == '(')
1108                 {
1109                         str++;
1110                         outer_inner_rels = OuterInnerRelsCreate(outer_inner_rels,
1111                                                                                                         NULL,
1112                                                                                                         NIL);
1113                         str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1114                 }
1115                 else if ((str = parse_quote_value_term_char(str, &name, truncate, '(')) == NULL)
1116                 {
1117                         list_free((*outer_inner)->outer_inner_pair);
1118                         return NULL;
1119                 }
1120                 else
1121                         outer_inner_rels = OuterInnerRelsCreate(outer_inner_rels, name, NIL);
1122
1123                 (*outer_inner)->outer_inner_pair = lappend(
1124                                                                                         (*outer_inner)->outer_inner_pair,
1125                                                                                          outer_inner_rels);
1126                 skip_space(str);
1127         }
1128
1129         str++;
1130
1131         return str;
1132 }
1133
1134 static const char *
1135 parse_parentheses_Leading(const char *str, List **name_list,
1136         OuterInnerRels **outer_inner)
1137 {
1138         char   *name;
1139         bool    truncate = true;
1140
1141         if ((str = skip_parenthesis(str, '(')) == NULL)
1142                 return NULL;
1143
1144         skip_space(str);
1145         if (*str =='(')
1146         {
1147                 str++;
1148
1149                 *outer_inner = OuterInnerRelsCreate(*outer_inner, NULL, NIL);
1150                 str = parse_parentheses_Leading_in(str, outer_inner);
1151         }
1152         else
1153         {
1154                 /* Store words in parentheses into name_list. */
1155                 while(*str != ')' && *str != '\0')
1156                 {
1157                         if ((str = parse_quote_value(str, &name, truncate)) == NULL)
1158                         {
1159                                 list_free(*name_list);
1160                                 return NULL;
1161                         }
1162
1163                         *name_list = lappend(*name_list, name);
1164                         skip_space(str);
1165                 }
1166         }
1167
1168         if ((str = skip_parenthesis(str, ')')) == NULL)
1169                 return NULL;
1170         return str;
1171 }
1172
1173 static const char *
1174 parse_parentheses(const char *str, List **name_list, HintType type)
1175 {
1176         char   *name;
1177         bool    truncate = true;
1178
1179         if ((str = skip_parenthesis(str, '(')) == NULL)
1180                 return NULL;
1181
1182         skip_space(str);
1183
1184         /* Store words in parentheses into name_list. */
1185         while(*str != ')' && *str != '\0')
1186         {
1187                 if ((str = parse_quote_value(str, &name, truncate)) == NULL)
1188                 {
1189                         list_free(*name_list);
1190                         return NULL;
1191                 }
1192
1193                 *name_list = lappend(*name_list, name);
1194                 skip_space(str);
1195
1196                 if (type == HINT_TYPE_SET)
1197                 {
1198                         truncate = false;
1199                 }
1200         }
1201
1202         if ((str = skip_parenthesis(str, ')')) == NULL)
1203                 return NULL;
1204         return str;
1205 }
1206
1207 static void
1208 parse_hints(HintState *hstate, Query *parse, const char *str)
1209 {
1210         StringInfoData  buf;
1211         char               *head;
1212
1213         initStringInfo(&buf);
1214         while (*str != '\0')
1215         {
1216                 const HintParser *parser;
1217
1218                 /* in error message, we output the comment including the keyword. */
1219                 head = (char *) str;
1220
1221                 /* parse only the keyword of the hint. */
1222                 resetStringInfo(&buf);
1223                 str = parse_keyword(str, &buf);
1224
1225                 for (parser = parsers; parser->keyword != NULL; parser++)
1226                 {
1227                         char   *keyword = parser->keyword;
1228                         Hint   *hint;
1229
1230                         if (strcasecmp(buf.data, keyword) != 0)
1231                                 continue;
1232
1233                         hint = parser->create_func(head, keyword, parser->hint_keyword);
1234
1235                         /* parser of each hint does parse in a parenthesis. */
1236                         if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1237                         {
1238                                 hint->delete_func(hint);
1239                                 pfree(buf.data);
1240                                 return;
1241                         }
1242
1243                         /*
1244                          * Add hint information into all_hints array.  If we don't have
1245                          * enough space, double the array.
1246                          */
1247                         if (hstate->nall_hints == 0)
1248                         {
1249                                 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1250                                 hstate->all_hints = (Hint **)
1251                                         palloc(sizeof(Hint *) * hstate->max_all_hints);
1252                         }
1253                         else if (hstate->nall_hints == hstate->max_all_hints)
1254                         {
1255                                 hstate->max_all_hints *= 2;
1256                                 hstate->all_hints = (Hint **)
1257                                         repalloc(hstate->all_hints,
1258                                                          sizeof(Hint *) * hstate->max_all_hints);
1259                         }
1260
1261                         hstate->all_hints[hstate->nall_hints] = hint;
1262                         hstate->nall_hints++;
1263
1264                         skip_space(str);
1265
1266                         break;
1267                 }
1268
1269                 if (parser->keyword == NULL)
1270                 {
1271                         hint_ereport(head,
1272                                                  ("Unrecognized hint keyword \"%s\".", buf.data));
1273                         pfree(buf.data);
1274                         return;
1275                 }
1276         }
1277
1278         pfree(buf.data);
1279 }
1280
1281 /*
1282  * Do basic parsing of the query head comment.
1283  */
1284 static HintState *
1285 parse_head_comment(Query *parse)
1286 {
1287         const char *p;
1288         char       *head;
1289         char       *tail;
1290         int                     len;
1291         int                     i;
1292         HintState   *hstate;
1293
1294         /* get client-supplied query string. */
1295         if (stmt_name)
1296         {
1297                 PreparedStatement  *entry;
1298
1299                 entry = FetchPreparedStatement(stmt_name, true);
1300                 p = entry->plansource->query_string;
1301         }
1302         else
1303                 p = debug_query_string;
1304
1305         if (p == NULL)
1306                 return NULL;
1307
1308         /* extract query head comment. */
1309         len = strlen(HINT_START);
1310         skip_space(p);
1311         if (strncmp(p, HINT_START, len))
1312                 return NULL;
1313
1314         head = (char *) p;
1315         p += len;
1316         skip_space(p);
1317
1318         /* find hint end keyword. */
1319         if ((tail = strstr(p, HINT_END)) == NULL)
1320         {
1321                 hint_ereport(head, ("Unterminated block comment."));
1322                 return NULL;
1323         }
1324
1325         /* We don't support nested block comments. */
1326         if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1327         {
1328                 hint_ereport(head, ("Nested block comments are not supported."));
1329                 return NULL;
1330         }
1331
1332         /* Make a copy of hint. */
1333         len = tail - p;
1334         head = palloc(len + 1);
1335         memcpy(head, p, len);
1336         head[len] = '\0';
1337         p = head;
1338
1339         hstate = HintStateCreate();
1340         hstate->hint_str = head;
1341
1342         /* parse each hint. */
1343         parse_hints(hstate, parse, p);
1344
1345         /* When nothing specified a hint, we free HintState and returns NULL. */
1346         if (hstate->nall_hints == 0)
1347         {
1348                 HintStateDelete(hstate);
1349                 return NULL;
1350         }
1351
1352         /* Sort hints in order of original position. */
1353         qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1354                   HintCmpWithPos);
1355
1356         /* Count number of hints per hint-type. */
1357         for (i = 0; i < hstate->nall_hints; i++)
1358         {
1359                 Hint   *cur_hint = hstate->all_hints[i];
1360                 hstate->num_hints[cur_hint->type]++;
1361         }
1362
1363         /*
1364          * If an object (or a set of objects) has multiple hints of same hint-type,
1365          * only the last hint is valid and others are igonred in planning.
1366          * Hints except the last are marked as 'duplicated' to remember the order.
1367          */
1368         for (i = 0; i < hstate->nall_hints - 1; i++)
1369         {
1370                 Hint   *cur_hint = hstate->all_hints[i];
1371                 Hint   *next_hint = hstate->all_hints[i + 1];
1372
1373                 /*
1374                  *  TODO : Leadingヒントの重複チェックは、transform_join_hints関数の実行
1375                  *       中に実施する。
1376                 */
1377                 if (i >= hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1378                             hstate->num_hints[HINT_TYPE_JOIN_METHOD] &&
1379                         i < hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1380                                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1381                                 hstate->num_hints[HINT_TYPE_LEADING])
1382                         continue;
1383
1384                 /*
1385                  * Note that we need to pass addresses of hint pointers, because
1386                  * HintCmp is designed to sort array of Hint* by qsort.
1387                  */
1388                 if (HintCmp(&cur_hint, &next_hint) == 0)
1389                 {
1390                         hint_ereport(cur_hint->hint_str,
1391                                                  ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1392                         cur_hint->state = HINT_STATE_DUPLICATION;
1393                 }
1394         }
1395
1396         /*
1397          * Make sure that per-type array pointers point proper position in the
1398          * array which consists of all hints.
1399          */
1400         hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1401         hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1402                 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1403         hstate->leading_hint = (LeadingHint **) hstate->all_hints +
1404                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1405                 hstate->num_hints[HINT_TYPE_JOIN_METHOD];
1406         hstate->set_hints = (SetHint **) hstate->all_hints +
1407                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1408                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1409                 hstate->num_hints[HINT_TYPE_LEADING];
1410
1411         return hstate;
1412 }
1413
1414 /*
1415  * Parse inside of parentheses of scan-method hints.
1416  */
1417 static const char *
1418 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1419                                         const char *str)
1420 {
1421         const char         *keyword = hint->base.keyword;
1422         HintKeyword             hint_keyword = hint->base.hint_keyword;
1423         List               *name_list = NIL;
1424         int                             length;
1425
1426         if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1427                 return NULL;
1428
1429         /* Parse relation name and index name(s) if given hint accepts. */
1430         length = list_length(name_list);
1431         if (length > 0)
1432         {
1433                 hint->relname = linitial(name_list);
1434                 hint->indexnames = list_delete_first(name_list);
1435
1436                 /* check whether the hint accepts index name(s). */
1437                 if (hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1438 #if PG_VERSION_NUM >= 90200
1439                         hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1440 #endif
1441                         hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1442                         length != 1)
1443                 {
1444                         hint_ereport(str,
1445                                                  ("%s hint accepts only one relation.",
1446                                                   hint->base.keyword));
1447                         hint->base.state = HINT_STATE_ERROR;
1448                         return str;
1449                 }
1450         }
1451         else
1452         {
1453                 hint_ereport(str,
1454                                          ("%s hint requires a relation.",
1455                                           hint->base.keyword));
1456                 hint->base.state = HINT_STATE_ERROR;
1457                 return str;
1458         }
1459
1460         /* Set a bit for specified hint. */
1461         switch (hint_keyword)
1462         {
1463                 case HINT_KEYWORD_SEQSCAN:
1464                         hint->enforce_mask = ENABLE_SEQSCAN;
1465                         break;
1466                 case HINT_KEYWORD_INDEXSCAN:
1467                         hint->enforce_mask = ENABLE_INDEXSCAN;
1468                         break;
1469                 case HINT_KEYWORD_BITMAPSCAN:
1470                         hint->enforce_mask = ENABLE_BITMAPSCAN;
1471                         break;
1472                 case HINT_KEYWORD_TIDSCAN:
1473                         hint->enforce_mask = ENABLE_TIDSCAN;
1474                         break;
1475                 case HINT_KEYWORD_NOSEQSCAN:
1476                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1477                         break;
1478                 case HINT_KEYWORD_NOINDEXSCAN:
1479                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1480                         break;
1481                 case HINT_KEYWORD_NOBITMAPSCAN:
1482                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1483                         break;
1484                 case HINT_KEYWORD_NOTIDSCAN:
1485                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1486                         break;
1487 #if PG_VERSION_NUM >= 90200
1488                 case HINT_KEYWORD_INDEXONLYSCAN:
1489                         hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1490                         break;
1491                 case HINT_KEYWORD_NOINDEXONLYSCAN:
1492                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1493                         break;
1494 #endif
1495                 default:
1496                         hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1497                         return NULL;
1498                         break;
1499         }
1500
1501         return str;
1502 }
1503
1504 static const char *
1505 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1506                                         const char *str)
1507 {
1508         const char         *keyword = hint->base.keyword;
1509         HintKeyword             hint_keyword = hint->base.hint_keyword;
1510         List               *name_list = NIL;
1511
1512         if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1513                 return NULL;
1514
1515         hint->nrels = list_length(name_list);
1516
1517         if (hint->nrels > 0)
1518         {
1519                 ListCell   *l;
1520                 int                     i = 0;
1521
1522                 /*
1523                  * Transform relation names from list to array to sort them with qsort
1524                  * after.
1525                  */
1526                 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1527                 foreach (l, name_list)
1528                 {
1529                         hint->relnames[i] = lfirst(l);
1530                         i++;
1531                 }
1532         }
1533
1534         list_free(name_list);
1535
1536         /* A join hint requires at least two relations */
1537         if (hint->nrels < 2)
1538         {
1539                 hint_ereport(str,
1540                                          ("%s hint requires at least two relations.",
1541                                           hint->base.keyword));
1542                 hint->base.state = HINT_STATE_ERROR;
1543                 return str;
1544         }
1545
1546         /* Sort hints in alphabetical order of relation names. */
1547         qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1548
1549         switch (hint_keyword)
1550         {
1551                 case HINT_KEYWORD_NESTLOOP:
1552                         hint->enforce_mask = ENABLE_NESTLOOP;
1553                         break;
1554                 case HINT_KEYWORD_MERGEJOIN:
1555                         hint->enforce_mask = ENABLE_MERGEJOIN;
1556                         break;
1557                 case HINT_KEYWORD_HASHJOIN:
1558                         hint->enforce_mask = ENABLE_HASHJOIN;
1559                         break;
1560                 case HINT_KEYWORD_NONESTLOOP:
1561                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1562                         break;
1563                 case HINT_KEYWORD_NOMERGEJOIN:
1564                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1565                         break;
1566                 case HINT_KEYWORD_NOHASHJOIN:
1567                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1568                         break;
1569                 default:
1570                         hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1571                         return NULL;
1572                         break;
1573         }
1574
1575         return str;
1576 }
1577
1578 static bool
1579 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1580 {
1581         ListCell *l;
1582         if (outer_inner->outer_inner_pair == NIL)
1583         {
1584                 if (outer_inner->relation)
1585                         return true;
1586                 else
1587                         return false;
1588         }
1589
1590         if (list_length(outer_inner->outer_inner_pair) == 2)
1591         {
1592                 foreach(l, outer_inner->outer_inner_pair)
1593                 {
1594                         if (!OuterInnerPairCheck(lfirst(l)))
1595                                 return false;
1596                 }
1597         }
1598         else
1599                 return false;
1600
1601         return true;
1602 }
1603
1604 static const char *
1605 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1606                                  const char *str)
1607 {
1608         List               *name_list = NIL;
1609         OuterInnerRels *outer_inner = NULL;
1610
1611         if ((str =
1612                  parse_parentheses_Leading(str, &name_list, &outer_inner)) == NULL)
1613                 return NULL;
1614
1615         hint->relations = name_list;
1616         hint->outer_inner = outer_inner;
1617
1618         /* A Leading hint requires at least two relations */
1619         if (list_length(hint->relations) < 2 && hint->outer_inner == NULL)
1620         {
1621                 hint_ereport(hint->base.hint_str,
1622                                          ("%s hint requires at least two relations.",
1623                                           HINT_LEADING));
1624                 hint->base.state = HINT_STATE_ERROR;
1625         }
1626         else if (hint->outer_inner != NULL &&
1627                          !OuterInnerPairCheck(hint->outer_inner))
1628         {
1629                 hint_ereport(hint->base.hint_str,
1630                                          ("%s hint requires two sets of relations when parentheses nests.",
1631                                           HINT_LEADING));
1632                 hint->base.state = HINT_STATE_ERROR;
1633         }
1634
1635         return str;
1636 }
1637
1638 static const char *
1639 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1640 {
1641         List   *name_list = NIL;
1642
1643         if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1644                 return NULL;
1645
1646         hint->words = name_list;
1647
1648         /* We need both name and value to set GUC parameter. */
1649         if (list_length(name_list) == 2)
1650         {
1651                 hint->name = linitial(name_list);
1652                 hint->value = lsecond(name_list);
1653         }
1654         else
1655         {
1656                 hint_ereport(hint->base.hint_str,
1657                                          ("%s hint requires name and value of GUC parameter.",
1658                                           HINT_SET));
1659                 hint->base.state = HINT_STATE_ERROR;
1660         }
1661
1662         return str;
1663 }
1664
1665 /*
1666  * set GUC parameter functions
1667  */
1668
1669 static int
1670 set_config_option_wrapper(const char *name, const char *value,
1671                                                   GucContext context, GucSource source,
1672                                                   GucAction action, bool changeVal, int elevel)
1673 {
1674         int                             result = 0;
1675         MemoryContext   ccxt = CurrentMemoryContext;
1676
1677         PG_TRY();
1678         {
1679 #if PG_VERSION_NUM >= 90200
1680                 result = set_config_option(name, value, context, source,
1681                                                                    action, changeVal, 0);
1682 #else
1683                 result = set_config_option(name, value, context, source,
1684                                                                    action, changeVal);
1685 #endif
1686         }
1687         PG_CATCH();
1688         {
1689                 ErrorData          *errdata;
1690
1691                 /* Save error info */
1692                 MemoryContextSwitchTo(ccxt);
1693                 errdata = CopyErrorData();
1694                 FlushErrorState();
1695
1696                 ereport(elevel, (errcode(errdata->sqlerrcode),
1697                                 errmsg("%s", errdata->message),
1698                                 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1699                                 errdata->hint ? errhint("%s", errdata->hint) : 0));
1700                 FreeErrorData(errdata);
1701         }
1702         PG_END_TRY();
1703
1704         return result;
1705 }
1706
1707 static int
1708 set_config_options(SetHint **options, int noptions, GucContext context)
1709 {
1710         int     i;
1711         int     save_nestlevel;
1712
1713         save_nestlevel = NewGUCNestLevel();
1714
1715         for (i = 0; i < noptions; i++)
1716         {
1717                 SetHint    *hint = options[i];
1718                 int                     result;
1719
1720                 if (!hint_state_enabled(hint))
1721                         continue;
1722
1723                 result = set_config_option_wrapper(hint->name, hint->value, context,
1724                                                                                    PGC_S_SESSION, GUC_ACTION_SAVE, true,
1725                                                                                    pg_hint_plan_parse_messages);
1726                 if (result != 0)
1727                         hint->base.state = HINT_STATE_USED;
1728                 else
1729                         hint->base.state = HINT_STATE_ERROR;
1730         }
1731
1732         return save_nestlevel;
1733 }
1734
1735 #define SET_CONFIG_OPTION(name, type_bits) \
1736         set_config_option_wrapper((name), \
1737                 (mask & (type_bits)) ? "true" : "false", \
1738                 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1739
1740 static void
1741 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1742 {
1743         unsigned char   mask;
1744
1745         if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1746                 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1747 #if PG_VERSION_NUM >= 90200
1748                 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1749 #endif
1750                 )
1751                 mask = enforce_mask;
1752         else
1753                 mask = enforce_mask & current_hint->init_scan_mask;
1754
1755         SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1756         SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1757         SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1758         SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1759 #if PG_VERSION_NUM >= 90200
1760         SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1761 #endif
1762 }
1763
1764 static void
1765 set_join_config_options(unsigned char enforce_mask, GucContext context)
1766 {
1767         unsigned char   mask;
1768
1769         if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1770                 enforce_mask == ENABLE_HASHJOIN)
1771                 mask = enforce_mask;
1772         else
1773                 mask = enforce_mask & current_hint->init_join_mask;
1774
1775         SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1776         SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1777         SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1778 }
1779
1780 /*
1781  * pg_hint_plan hook functions
1782  */
1783
1784 static void
1785 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1786                                                         ParamListInfo params, bool isTopLevel,
1787                                                         DestReceiver *dest, char *completionTag)
1788 {
1789         Node                               *node;
1790
1791         if (!pg_hint_plan_enable_hint)
1792         {
1793                 if (prev_ProcessUtility)
1794                         (*prev_ProcessUtility) (parsetree, queryString, params,
1795                                                                         isTopLevel, dest, completionTag);
1796                 else
1797                         standard_ProcessUtility(parsetree, queryString, params,
1798                                                                         isTopLevel, dest, completionTag);
1799
1800                 return;
1801         }
1802
1803         node = parsetree;
1804         if (IsA(node, ExplainStmt))
1805         {
1806                 /*
1807                  * Draw out parse tree of actual query from Query struct of EXPLAIN
1808                  * statement.
1809                  */
1810                 ExplainStmt        *stmt;
1811                 Query              *query;
1812
1813                 stmt = (ExplainStmt *) node;
1814
1815                 Assert(IsA(stmt->query, Query));
1816                 query = (Query *) stmt->query;
1817
1818                 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1819                         node = query->utilityStmt;
1820         }
1821
1822         /*
1823          * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1824          * specified to preceding PREPARE command to use it as source of hints.
1825          */
1826         if (IsA(node, ExecuteStmt))
1827         {
1828                 ExecuteStmt        *stmt;
1829
1830                 stmt = (ExecuteStmt *) node;
1831                 stmt_name = stmt->name;
1832         }
1833 #if PG_VERSION_NUM >= 90200
1834         /*
1835          * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1836          * specially here.
1837          */
1838         if (IsA(node, CreateTableAsStmt))
1839         {
1840                 CreateTableAsStmt          *stmt;
1841                 Query              *query;
1842
1843                 stmt = (CreateTableAsStmt *) node;
1844                 Assert(IsA(stmt->query, Query));
1845                 query = (Query *) stmt->query;
1846
1847                 if (query->commandType == CMD_UTILITY &&
1848                         IsA(query->utilityStmt, ExecuteStmt))
1849                 {
1850                         ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1851                         stmt_name = estmt->name;
1852                 }
1853         }
1854 #endif
1855         if (stmt_name)
1856         {
1857                 PG_TRY();
1858                 {
1859                         if (prev_ProcessUtility)
1860                                 (*prev_ProcessUtility) (parsetree, queryString, params,
1861                                                                                 isTopLevel, dest, completionTag);
1862                         else
1863                                 standard_ProcessUtility(parsetree, queryString, params,
1864                                                                                 isTopLevel, dest, completionTag);
1865                 }
1866                 PG_CATCH();
1867                 {
1868                         stmt_name = NULL;
1869                         PG_RE_THROW();
1870                 }
1871                 PG_END_TRY();
1872
1873                 stmt_name = NULL;
1874
1875                 return;
1876         }
1877
1878         if (prev_ProcessUtility)
1879                 (*prev_ProcessUtility) (parsetree, queryString, params,
1880                                                                 isTopLevel, dest, completionTag);
1881         else
1882                 standard_ProcessUtility(parsetree, queryString, params,
1883                                                                 isTopLevel, dest, completionTag);
1884 }
1885
1886 /*
1887  * Push a hint into hint stack which is implemented with List struct.  Head of
1888  * list is top of stack.
1889  */
1890 static void
1891 push_hint(HintState *hstate)
1892 {
1893         /* Prepend new hint to the list means pushing to stack. */
1894         HintStateStack = lcons(hstate, HintStateStack);
1895
1896         /* Pushed hint is the one which should be used hereafter. */
1897         current_hint = hstate;
1898 }
1899
1900 /* Pop a hint from hint stack.  Popped hint is automatically discarded. */
1901 static void
1902 pop_hint(void)
1903 {
1904         /* Hint stack must not be empty. */
1905         if(HintStateStack == NIL)
1906                 elog(ERROR, "hint stack is empty");
1907
1908         /*
1909          * Take a hint at the head from the list, and free it.  Switch current_hint
1910          * to point new head (NULL if the list is empty).
1911          */
1912         HintStateStack = list_delete_first(HintStateStack);
1913         HintStateDelete(current_hint);
1914         if(HintStateStack == NIL)
1915                 current_hint = NULL;
1916         else
1917                 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1918 }
1919
1920 static PlannedStmt *
1921 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1922 {
1923         int                             save_nestlevel;
1924         PlannedStmt        *result;
1925         HintState          *hstate;
1926
1927         /*
1928          * Use standard planner if pg_hint_plan is disabled.  Other hook functions
1929          * try to change plan with current_hint if any, so set it to NULL.
1930          */
1931         if (!pg_hint_plan_enable_hint)
1932         {
1933                 current_hint = NULL;
1934
1935                 if (prev_planner)
1936                         return (*prev_planner) (parse, cursorOptions, boundParams);
1937                 else
1938                         return standard_planner(parse, cursorOptions, boundParams);
1939         }
1940
1941         /* Create hint struct from parse tree. */
1942         hstate = parse_head_comment(parse);
1943
1944         /*
1945          * Use standard planner if the statement has not valid hint.  Other hook
1946          * functions try to change plan with current_hint if any, so set it to
1947          * NULL.
1948          */
1949         if (!hstate)
1950         {
1951                 current_hint = NULL;
1952
1953                 if (prev_planner)
1954                         return (*prev_planner) (parse, cursorOptions, boundParams);
1955                 else
1956                         return standard_planner(parse, cursorOptions, boundParams);
1957         }
1958
1959         /*
1960          * Push new hint struct to the hint stack to disable previous hint context.
1961          */
1962         push_hint(hstate);
1963
1964         /* Set GUC parameters which are specified with Set hint. */
1965         save_nestlevel = set_config_options(current_hint->set_hints,
1966                                                                                 current_hint->num_hints[HINT_TYPE_SET],
1967                                                                                 current_hint->context);
1968
1969         if (enable_seqscan)
1970                 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1971         if (enable_indexscan)
1972                 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1973         if (enable_bitmapscan)
1974                 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1975         if (enable_tidscan)
1976                 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1977 #if PG_VERSION_NUM >= 90200
1978         if (enable_indexonlyscan)
1979                 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1980 #endif
1981         if (enable_nestloop)
1982                 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1983         if (enable_mergejoin)
1984                 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1985         if (enable_hashjoin)
1986                 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1987
1988         /*
1989          * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1990          * state when this planner started when error occurred in planner.
1991          */
1992         PG_TRY();
1993         {
1994                 if (prev_planner)
1995                         result = (*prev_planner) (parse, cursorOptions, boundParams);
1996                 else
1997                         result = standard_planner(parse, cursorOptions, boundParams);
1998         }
1999         PG_CATCH();
2000         {
2001                 /*
2002                  * Rollback changes of GUC parameters, and pop current hint context
2003                  * from hint stack to rewind the state.
2004                  */
2005                 AtEOXact_GUC(true, save_nestlevel);
2006                 pop_hint();
2007                 PG_RE_THROW();
2008         }
2009         PG_END_TRY();
2010
2011         /* Print hint in debug mode. */
2012         if (pg_hint_plan_debug_print)
2013                 HintStateDump(current_hint);
2014
2015         /*
2016          * Rollback changes of GUC parameters, and pop current hint context from
2017          * hint stack to rewind the state.
2018          */
2019         AtEOXact_GUC(true, save_nestlevel);
2020         pop_hint();
2021
2022         return result;
2023 }
2024
2025 /*
2026  * Return scan method hint which matches given aliasname.
2027  */
2028 static ScanMethodHint *
2029 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2030 {
2031         RangeTblEntry  *rte;
2032         int                             i;
2033
2034         /*
2035          * We can't apply scan method hint if the relation is:
2036          *   - not a base relation
2037          *   - not an ordinary relation (such as join and subquery)
2038          */
2039         if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2040                 return NULL;
2041
2042         rte = root->simple_rte_array[rel->relid];
2043
2044         /* We can't force scan method of foreign tables */
2045         if (rte->relkind == RELKIND_FOREIGN_TABLE)
2046                 return NULL;
2047
2048         /* Find scan method hint, which matches given names, from the list. */
2049         for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2050         {
2051                 ScanMethodHint *hint = current_hint->scan_hints[i];
2052
2053                 /* We ignore disabled hints. */
2054                 if (!hint_state_enabled(hint))
2055                         continue;
2056
2057                 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2058                         return hint;
2059         }
2060
2061         return NULL;
2062 }
2063
2064 static void
2065 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2066 {
2067         ListCell           *cell;
2068         ListCell           *prev;
2069         ListCell           *next;
2070         StringInfoData  buf;
2071
2072         /*
2073          * We delete all the IndexOptInfo list and prevent you from being usable by
2074          * a scan.
2075          */
2076         if (hint->enforce_mask == ENABLE_SEQSCAN ||
2077                 hint->enforce_mask == ENABLE_TIDSCAN)
2078         {
2079                 list_free_deep(rel->indexlist);
2080                 rel->indexlist = NIL;
2081                 hint->base.state = HINT_STATE_USED;
2082
2083                 return;
2084         }
2085
2086         /*
2087          * When a list of indexes is not specified, we just use all indexes.
2088          */
2089         if (hint->indexnames == NIL)
2090                 return;
2091
2092         /*
2093          * Leaving only an specified index, we delete it from a IndexOptInfo list
2094          * other than it.
2095          */
2096         prev = NULL;
2097         if (pg_hint_plan_debug_print)
2098                 initStringInfo(&buf);
2099
2100         for (cell = list_head(rel->indexlist); cell; cell = next)
2101         {
2102                 IndexOptInfo   *info = (IndexOptInfo *) lfirst(cell);
2103                 char               *indexname = get_rel_name(info->indexoid);
2104                 ListCell           *l;
2105                 bool                    use_index = false;
2106
2107                 next = lnext(cell);
2108
2109                 foreach(l, hint->indexnames)
2110                 {
2111                         if (RelnameCmp(&indexname, &lfirst(l)) == 0)
2112                         {
2113                                 use_index = true;
2114                                 if (pg_hint_plan_debug_print)
2115                                 {
2116                                         appendStringInfoCharMacro(&buf, ' ');
2117                                         dump_quote_value(&buf, indexname);
2118                                 }
2119
2120                                 break;
2121                         }
2122                 }
2123
2124                 if (!use_index)
2125                         rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2126                 else
2127                         prev = cell;
2128
2129                 pfree(indexname);
2130         }
2131
2132         if (pg_hint_plan_debug_print)
2133         {
2134                 char   *relname;
2135                 StringInfoData  rel_buf;
2136
2137                 if (OidIsValid(relationObjectId))
2138                         relname = get_rel_name(relationObjectId);
2139                 else
2140                         relname = hint->relname;
2141
2142                 initStringInfo(&rel_buf);
2143                 dump_quote_value(&rel_buf, relname);
2144
2145                 ereport(LOG,
2146                                 (errmsg("available indexes for %s(%s):%s",
2147                                          hint->base.keyword,
2148                                          rel_buf.data,
2149                                          buf.data)));
2150                 pfree(buf.data);
2151                 pfree(rel_buf.data);
2152         }
2153 }
2154
2155 static void
2156 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2157                                                            bool inhparent, RelOptInfo *rel)
2158 {
2159         ScanMethodHint *hint;
2160
2161         if (prev_get_relation_info)
2162                 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2163
2164         /* Do nothing if we don't have valid hint in this context. */
2165         if (!current_hint)
2166                 return;
2167
2168         if (inhparent)
2169         {
2170                 /* store does relids of parent table. */
2171                 current_hint->parent_relid = rel->relid;
2172         }
2173         else if (current_hint->parent_relid != 0)
2174         {
2175                 /*
2176                  * We use the same GUC parameter if this table is the child table of a
2177                  * table called pg_hint_plan_get_relation_info just before that.
2178                  */
2179                 ListCell   *l;
2180
2181                 /* append_rel_list contains all append rels; ignore others */
2182                 foreach(l, root->append_rel_list)
2183                 {
2184                         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2185
2186                         /* This rel is child table. */
2187                         if (appinfo->parent_relid == current_hint->parent_relid &&
2188                                 appinfo->child_relid == rel->relid)
2189                         {
2190                                 if (current_hint->parent_hint)
2191                                         delete_indexes(current_hint->parent_hint, rel,
2192                                                                    relationObjectId);
2193
2194                                 return;
2195                         }
2196                 }
2197
2198                 /* This rel is not inherit table. */
2199                 current_hint->parent_relid = 0;
2200                 current_hint->parent_hint = NULL;
2201         }
2202
2203         /*
2204          * If scan method hint was given, reset GUC parameters which control
2205          * planner behavior about choosing scan methods.
2206          */
2207         if ((hint = find_scan_hint(root, rel)) == NULL)
2208         {
2209                 set_scan_config_options(current_hint->init_scan_mask,
2210                                                                 current_hint->context);
2211                 return;
2212         }
2213         set_scan_config_options(hint->enforce_mask, current_hint->context);
2214         hint->base.state = HINT_STATE_USED;
2215         if (inhparent)
2216                 current_hint->parent_hint = hint;
2217         else
2218                 delete_indexes(hint, rel, InvalidOid);
2219 }
2220
2221 /*
2222  * Return index of relation which matches given aliasname, or 0 if not found.
2223  * If same aliasname was used multiple times in a query, return -1.
2224  */
2225 static int
2226 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2227                                          const char *str)
2228 {
2229         int             i;
2230         Index   found = 0;
2231
2232         for (i = 1; i < root->simple_rel_array_size; i++)
2233         {
2234                 ListCell   *l;
2235
2236                 if (root->simple_rel_array[i] == NULL)
2237                         continue;
2238
2239                 Assert(i == root->simple_rel_array[i]->relid);
2240
2241                 if (RelnameCmp(&aliasname,
2242                                            &root->simple_rte_array[i]->eref->aliasname) != 0)
2243                         continue;
2244
2245                 foreach(l, initial_rels)
2246                 {
2247                         RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2248
2249                         if (rel->reloptkind == RELOPT_BASEREL)
2250                         {
2251                                 if (rel->relid != i)
2252                                         continue;
2253                         }
2254                         else
2255                         {
2256                                 Assert(rel->reloptkind == RELOPT_JOINREL);
2257
2258                                 if (!bms_is_member(i, rel->relids))
2259                                         continue;
2260                         }
2261
2262                         if (found != 0)
2263                         {
2264                                 hint_ereport(str,
2265                                                          ("Relation name \"%s\" is ambiguous.",
2266                                                           aliasname));
2267                                 return -1;
2268                         }
2269
2270                         found = i;
2271                         break;
2272                 }
2273
2274         }
2275
2276         return found;
2277 }
2278
2279 /*
2280  * Return join hint which matches given joinrelids.
2281  */
2282 static JoinMethodHint *
2283 find_join_hint(Relids joinrelids)
2284 {
2285         List       *join_hint;
2286         ListCell   *l;
2287
2288         join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2289
2290         foreach(l, join_hint)
2291         {
2292                 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2293
2294                 if (bms_equal(joinrelids, hint->joinrelids))
2295                         return hint;
2296         }
2297
2298         return NULL;
2299 }
2300
2301 static List *
2302 OuterInnerList(OuterInnerRels *outer_inner)
2303 {
2304         List               *outer_inner_list = NIL;
2305         ListCell           *l;
2306         OuterInnerRels *outer_inner_rels;
2307
2308         foreach(l, outer_inner->outer_inner_pair)
2309         {
2310                 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2311
2312                 if (outer_inner_rels->relation != NULL)
2313                         outer_inner_list = lappend(outer_inner_list,
2314                                                                            outer_inner_rels->relation);
2315                 else
2316                         outer_inner_list = list_concat(outer_inner_list,
2317                                                                                    OuterInnerList(outer_inner_rels));
2318         }
2319         return outer_inner_list;
2320 }
2321
2322 static Relids
2323 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2324         PlannerInfo *root, List *initial_rels, HintState *hstate, int *njoinrels,
2325         int nbaserel)
2326 {
2327         OuterInnerRels *outer_rels;
2328         OuterInnerRels *inner_rels;
2329         Relids                  outer_relids;
2330         Relids                  inner_relids;
2331         Relids                  join_relids;
2332         JoinMethodHint *hint;
2333
2334         if (outer_inner->relation != NULL)
2335         {
2336                 (*njoinrels)++;
2337                 return bms_make_singleton(
2338                                         find_relid_aliasname(root, outer_inner->relation,
2339                                                                                  initial_rels,
2340                                                                                  leading_hint->base.hint_str));
2341         }
2342
2343         outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2344         inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2345
2346         outer_relids = OuterInnerJoinCreate(outer_rels,
2347                                                                                 leading_hint,
2348                                                                                 root,
2349                                                                                 initial_rels,
2350                                                                                 hstate,
2351                                                                                 njoinrels,
2352                                                                                 nbaserel);
2353         inner_relids = OuterInnerJoinCreate(inner_rels,
2354                                                                                 leading_hint,
2355                                                                                 root,
2356                                                                                 initial_rels,
2357                                                                                 hstate,
2358                                                                                 njoinrels,
2359                                                                                 nbaserel);
2360
2361         join_relids = bms_add_members(outer_relids, inner_relids);
2362
2363         if (bms_num_members(join_relids) > nbaserel || *njoinrels > nbaserel)
2364                 return join_relids;
2365
2366         /*
2367          * If we don't have join method hint, create new one for the
2368          * join combination with all join methods are enabled.
2369          */
2370         hint = find_join_hint(join_relids);
2371         if (hint == NULL)
2372         {
2373                 /*
2374                  * Here relnames is not set, since Relids bitmap is sufficient to
2375                  * control paths of this query afterward.
2376                  */
2377                 hint = (JoinMethodHint *) JoinMethodHintCreate(
2378                                         leading_hint->base.hint_str,
2379                                         HINT_LEADING,
2380                                         HINT_KEYWORD_LEADING);
2381                 hint->base.state = HINT_STATE_USED;
2382                 hint->nrels = bms_num_members(join_relids);
2383                 hint->enforce_mask = ENABLE_ALL_JOIN;
2384                 hint->joinrelids = bms_copy(join_relids);
2385                 hint->inner_nrels = bms_num_members(inner_relids);
2386                 hint->inner_joinrelids = bms_copy(inner_relids);
2387
2388                 hstate->join_hint_level[hint->nrels] =
2389                         lappend(hstate->join_hint_level[hint->nrels], hint);
2390         }
2391         else
2392         {
2393                 hint->inner_nrels = bms_num_members(inner_relids);
2394                 hint->inner_joinrelids = bms_copy(inner_relids);
2395         }
2396
2397         return join_relids;
2398 }
2399
2400 /*
2401  * Transform join method hint into handy form.
2402  *
2403  *   - create bitmap of relids from alias names, to make it easier to check
2404  *     whether a join path matches a join method hint.
2405  *   - add join method hints which are necessary to enforce join order
2406  *     specified by Leading hint
2407  */
2408 static void
2409 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2410                 List *initial_rels, JoinMethodHint **join_method_hints,
2411                 LeadingHint *lhint)
2412 {
2413         int                             i;
2414         int                             relid;
2415         Relids                  joinrelids;
2416         int                             njoinrels;
2417         ListCell           *l;
2418         char               *relname;
2419         bool                    exist_effective_leading;
2420
2421         /*
2422          * Create bitmap of relids from alias names for each join method hint.
2423          * Bitmaps are more handy than strings in join searching.
2424          */
2425         for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2426         {
2427                 JoinMethodHint *hint = hstate->join_hints[i];
2428                 int     j;
2429
2430                 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2431                         continue;
2432
2433                 bms_free(hint->joinrelids);
2434                 hint->joinrelids = NULL;
2435                 relid = 0;
2436                 for (j = 0; j < hint->nrels; j++)
2437                 {
2438                         relname = hint->relnames[j];
2439
2440                         relid = find_relid_aliasname(root, relname, initial_rels,
2441                                                                                  hint->base.hint_str);
2442
2443                         if (relid == -1)
2444                                 hint->base.state = HINT_STATE_ERROR;
2445
2446                         if (relid <= 0)
2447                                 break;
2448
2449                         if (bms_is_member(relid, hint->joinrelids))
2450                         {
2451                                 hint_ereport(hint->base.hint_str,
2452                                                          ("Relation name \"%s\" is duplicated.", relname));
2453                                 hint->base.state = HINT_STATE_ERROR;
2454                                 break;
2455                         }
2456
2457                         hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2458                 }
2459
2460                 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2461                         continue;
2462
2463                 hstate->join_hint_level[hint->nrels] =
2464                         lappend(hstate->join_hint_level[hint->nrels], hint);
2465         }
2466
2467         /* Do nothing if no Leading hint was supplied. */
2468         if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2469                 return;
2470
2471         /*
2472          * Decide to use Leading hint。
2473          */
2474         exist_effective_leading = false;
2475         for (i = hstate->num_hints[HINT_TYPE_LEADING] - 1; i >= 0; i--) {
2476                 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2477
2478                 List *relname_list;
2479                 Relids  relids;
2480
2481                 if (leading_hint->base.state == HINT_STATE_ERROR)
2482                         continue;
2483
2484                 if (leading_hint->outer_inner != NULL)
2485                         relname_list = OuterInnerList(leading_hint->outer_inner);
2486                 else
2487                         relname_list = leading_hint->relations;
2488
2489                 relid = 0;
2490                 relids = 0;
2491
2492                 foreach(l, relname_list)
2493                 {
2494                         relname = (char *)lfirst(l);;
2495
2496                         relid = find_relid_aliasname(root, relname, initial_rels,
2497                                                                                  leading_hint->base.hint_str);
2498                         if (relid == -1)
2499                                 leading_hint->base.state = HINT_STATE_ERROR;
2500
2501                         if (relid <= 0)
2502                                 break;
2503
2504                         if (bms_is_member(relid, relids))
2505                         {
2506                                 hint_ereport(leading_hint->base.hint_str,
2507                                                          ("Relation name \"%s\" is duplicated.", relname));
2508                                 leading_hint->base.state = HINT_STATE_ERROR;
2509                                 break;
2510                         }
2511
2512                         relids = bms_add_member(relids, relid);
2513                 }
2514
2515                 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
2516                         continue;
2517
2518                 if (exist_effective_leading)
2519                 {
2520                         hint_ereport(leading_hint->base.hint_str,
2521                                  ("Conflict %s hint.", HintTypeName[leading_hint->base.type]));
2522                         leading_hint->base.state = HINT_STATE_DUPLICATION;
2523                 }
2524                 else
2525                 {
2526                         leading_hint->base.state = HINT_STATE_USED;
2527                         exist_effective_leading = true;
2528                         lhint = leading_hint;
2529                 }
2530         }
2531         if (exist_effective_leading == false)
2532                 return;
2533
2534         /*
2535          * We need join method hints which fit specified join order in every join
2536          * level.  For example, Leading(A B C) virtually requires following join
2537          * method hints, if no join method hint supplied:
2538          *   - level 1: none
2539          *   - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2540          *   - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2541          *
2542          * If we already have join method hint which fits specified join order in
2543          * that join level, we leave it as-is and don't add new hints.
2544          */
2545         joinrelids = NULL;
2546         njoinrels = 0;
2547         if (lhint->outer_inner == NULL)
2548         {
2549                 foreach(l, lhint->relations)
2550                 {
2551                         JoinMethodHint *hint;
2552
2553                         relname = (char *)lfirst(l);
2554
2555                         /*
2556                          * Find relid of the relation which has given name.  If we have the
2557                          * name given in Leading hint multiple times in the join, nothing to
2558                          * do.
2559                          */
2560                         relid = find_relid_aliasname(root, relname, initial_rels,
2561                                                                                  hstate->hint_str);
2562
2563                         /* Create bitmap of relids for current join level. */
2564                         joinrelids = bms_add_member(joinrelids, relid);
2565                         njoinrels++;
2566
2567                         /* We never have join method hint for single relation. */
2568                         if (njoinrels < 2)
2569                                 continue;
2570
2571                         /*
2572                          * If we don't have join method hint, create new one for the
2573                          * join combination with all join methods are enabled.
2574                          */
2575                         hint = find_join_hint(joinrelids);
2576                         if (hint == NULL)
2577                         {
2578                                 /*
2579                                  * Here relnames is not set, since Relids bitmap is sufficient
2580                                  * to control paths of this query afterward.
2581                                  */
2582                                 hint = (JoinMethodHint *) JoinMethodHintCreate(
2583                                                                                         lhint->base.hint_str,
2584                                                                                         HINT_LEADING,
2585                                                                                         HINT_KEYWORD_LEADING);
2586                                 hint->base.state = HINT_STATE_USED;
2587                                 hint->nrels = njoinrels;
2588                                 hint->enforce_mask = ENABLE_ALL_JOIN;
2589                                 hint->joinrelids = bms_copy(joinrelids);
2590                         }
2591
2592                         join_method_hints[njoinrels] = hint;
2593
2594                         if (njoinrels >= nbaserel)
2595                                 break;
2596                 }
2597                 bms_free(joinrelids);
2598
2599                 if (njoinrels < 2)
2600                         return;
2601
2602                 /*
2603                  * Delete all join hints which have different combination from Leading
2604                  * hint.
2605                  */
2606                 for (i = 2; i <= njoinrels; i++)
2607                 {
2608                         list_free(hstate->join_hint_level[i]);
2609
2610                         hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2611                 }
2612         }
2613         else
2614         {
2615                 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
2616                                                                                   lhint,
2617                                           root,
2618                                           initial_rels,
2619                                                                                   hstate,
2620                                          &njoinrels,
2621                                                                                   nbaserel);
2622
2623                 /*
2624                  * Delete all join hints which have different combination from Leading
2625                  * hint.
2626                  */
2627                 for (i = 2;i <= nbaserel; i++)
2628                 {
2629                         if (hstate->join_hint_level[i] != NIL)
2630                         {
2631                                 ListCell *prev = NULL;
2632                                 ListCell *next = NULL;
2633                                 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
2634                                 {
2635
2636                                         JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
2637
2638                                         next = lnext(l);
2639
2640                                         if (hint->inner_nrels == 0 &&
2641                                                 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
2642                                                   bms_equal(bms_union(hint->joinrelids, joinrelids),
2643                                                   hint->joinrelids)))
2644                                         {
2645                                                 hstate->join_hint_level[i] =
2646                                                         list_delete_cell(hstate->join_hint_level[i], l,
2647                                                                                          prev);
2648                                         }
2649                                         else
2650                                                 prev = l;
2651                                 }
2652                         }
2653                 }
2654
2655         bms_free(joinrelids);
2656
2657         if (njoinrels < 2)
2658                 return;
2659         }
2660
2661         if (hint_state_enabled(lhint))
2662                 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2663 }
2664
2665 /*
2666  * set_plain_rel_pathlist
2667  *        Build access paths for a plain relation (no subquery, no inheritance)
2668  *
2669  * This function was copied and edited from set_plain_rel_pathlist() in
2670  * src/backend/optimizer/path/allpaths.c
2671  */
2672 static void
2673 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2674 {
2675         /* Consider sequential scan */
2676 #if PG_VERSION_NUM >= 90200
2677         add_path(rel, create_seqscan_path(root, rel, NULL));
2678 #else
2679         add_path(rel, create_seqscan_path(root, rel));
2680 #endif
2681
2682         /* Consider index scans */
2683         create_index_paths(root, rel);
2684
2685         /* Consider TID scans */
2686         create_tidscan_paths(root, rel);
2687
2688         /* Now find the cheapest of the paths for this rel */
2689         set_cheapest(rel);
2690 }
2691
2692 static void
2693 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2694                                   List *initial_rels)
2695 {
2696         ListCell   *l;
2697
2698         foreach(l, initial_rels)
2699         {
2700                 RelOptInfo         *rel = (RelOptInfo *) lfirst(l);
2701                 RangeTblEntry  *rte;
2702                 ScanMethodHint *hint;
2703
2704                 /* Skip relations which we can't choose scan method. */
2705                 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2706                         continue;
2707
2708                 rte = root->simple_rte_array[rel->relid];
2709
2710                 /* We can't force scan method of foreign tables */
2711                 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2712                         continue;
2713
2714                 /*
2715                  * Create scan paths with GUC parameters which are at the beginning of
2716                  * planner if scan method hint is not specified, otherwise use
2717                  * specified hints and mark the hint as used.
2718                  */
2719                 if ((hint = find_scan_hint(root, rel)) == NULL)
2720                         set_scan_config_options(hstate->init_scan_mask,
2721                                                                         hstate->context);
2722                 else
2723                 {
2724                         set_scan_config_options(hint->enforce_mask, hstate->context);
2725                         hint->base.state = HINT_STATE_USED;
2726                 }
2727
2728                 list_free_deep(rel->pathlist);
2729                 rel->pathlist = NIL;
2730                 if (rte->inh)
2731                 {
2732                         /* It's an "append relation", process accordingly */
2733                         set_append_rel_pathlist(root, rel, rel->relid, rte);
2734                 }
2735                 else
2736                 {
2737                         set_plain_rel_pathlist(root, rel, rte);
2738                 }
2739         }
2740
2741         /*
2742          * Restore the GUC variables we set above.
2743          */
2744         set_scan_config_options(hstate->init_scan_mask, hstate->context);
2745 }
2746
2747 /*
2748  * wrapper of make_join_rel()
2749  *
2750  * call make_join_rel() after changing enable_* parameters according to given
2751  * hints.
2752  */
2753 static RelOptInfo *
2754 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2755 {
2756         Relids                  joinrelids;
2757         JoinMethodHint *hint;
2758         RelOptInfo         *rel;
2759         int                             save_nestlevel;
2760
2761         joinrelids = bms_union(rel1->relids, rel2->relids);
2762         hint = find_join_hint(joinrelids);
2763         bms_free(joinrelids);
2764
2765         if (!hint)
2766                 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2767
2768         if (hint->inner_nrels == 0)
2769         {
2770                 save_nestlevel = NewGUCNestLevel();
2771
2772                 set_join_config_options(hint->enforce_mask, current_hint->context);
2773
2774                 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2775                 hint->base.state = HINT_STATE_USED;
2776
2777                 /*
2778                  * Restore the GUC variables we set above.
2779                  */
2780                 AtEOXact_GUC(true, save_nestlevel);
2781         }
2782         else
2783                 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2784
2785         return rel;
2786 }
2787
2788 /*
2789  * TODO : comment
2790  */
2791 static void
2792 add_paths_to_joinrel_wrapper(PlannerInfo *root,
2793                                                          RelOptInfo *joinrel,
2794                                                          RelOptInfo *outerrel,
2795                                                          RelOptInfo *innerrel,
2796                                                          JoinType jointype,
2797                                                          SpecialJoinInfo *sjinfo,
2798                                                          List *restrictlist)
2799 {
2800         ScanMethodHint *scan_hint = NULL;
2801         Relids                  joinrelids;
2802         JoinMethodHint *join_hint;
2803         int                             save_nestlevel;
2804
2805         if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
2806         {
2807                 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
2808                 scan_hint->base.state = HINT_STATE_USED;
2809         }
2810
2811         joinrelids = bms_union(outerrel->relids, innerrel->relids);
2812         join_hint = find_join_hint(joinrelids);
2813         bms_free(joinrelids);
2814
2815         if (join_hint && join_hint->inner_nrels != 0)
2816         {
2817                 save_nestlevel = NewGUCNestLevel();
2818
2819                 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
2820                 {
2821
2822                         set_join_config_options(join_hint->enforce_mask,
2823                                                                         current_hint->context);
2824
2825                         add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2826                                                                  sjinfo, restrictlist);
2827                         join_hint->base.state = HINT_STATE_USED;
2828                 }
2829                 else
2830                 {
2831                         set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2832                         add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2833                                                                  sjinfo, restrictlist);
2834                 }
2835
2836                 /*
2837                  * Restore the GUC variables we set above.
2838                  */
2839                 AtEOXact_GUC(true, save_nestlevel);
2840         }
2841         else
2842                 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2843                                                          sjinfo, restrictlist);
2844
2845         if (scan_hint != NULL)
2846                 set_scan_config_options(current_hint->init_scan_mask,
2847                                                                 current_hint->context);
2848 }
2849
2850 static int
2851 get_num_baserels(List *initial_rels)
2852 {
2853         int                     nbaserel = 0;
2854         ListCell   *l;
2855
2856         foreach(l, initial_rels)
2857         {
2858                 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2859
2860                 if (rel->reloptkind == RELOPT_BASEREL)
2861                         nbaserel++;
2862                 else if (rel->reloptkind ==RELOPT_JOINREL)
2863                         nbaserel+= bms_num_members(rel->relids);
2864                 else
2865                 {
2866                         /* other values not expected here */
2867                         elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2868                 }
2869         }
2870
2871         return nbaserel;
2872 }
2873
2874 static RelOptInfo *
2875 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2876                                                  List *initial_rels)
2877 {
2878         JoinMethodHint    **join_method_hints;
2879         LeadingHint                *leading_hint = NULL;
2880         int                                     nbaserel;
2881         RelOptInfo                 *rel;
2882         int                                     i;
2883
2884         /*
2885          * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2886          * valid hint is supplied.
2887          */
2888         if (!current_hint)
2889         {
2890                 if (prev_join_search)
2891                         return (*prev_join_search) (root, levels_needed, initial_rels);
2892                 else if (enable_geqo && levels_needed >= geqo_threshold)
2893                         return geqo(root, levels_needed, initial_rels);
2894                 else
2895                         return standard_join_search(root, levels_needed, initial_rels);
2896         }
2897
2898         /* We apply scan method hint rebuild scan path. */
2899         rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2900
2901         /*
2902          * In the case using GEQO, only scan method hints and Set hints have
2903          * effect.  Join method and join order is not controllable by hints.
2904          */
2905         if (enable_geqo && levels_needed >= geqo_threshold)
2906                 return geqo(root, levels_needed, initial_rels);
2907
2908         nbaserel = get_num_baserels(initial_rels);
2909         current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2910         join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2911
2912         transform_join_hints(current_hint, root, nbaserel, initial_rels,
2913                                                  join_method_hints, leading_hint);
2914
2915         rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2916
2917         for (i = 2; i <= nbaserel; i++)
2918         {
2919                 list_free(current_hint->join_hint_level[i]);
2920
2921                 /* free Leading hint only */
2922                 if (join_method_hints[i] != NULL &&
2923                         join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2924                         JoinMethodHintDelete(join_method_hints[i]);
2925         }
2926         pfree(current_hint->join_hint_level);
2927         pfree(join_method_hints);
2928
2929         if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2930                 leading_hint != NULL &&
2931                 hint_state_enabled(leading_hint))
2932                 set_join_config_options(current_hint->init_join_mask,
2933                                                                 current_hint->context);
2934
2935         return rel;
2936 }
2937
2938 /*
2939  * set_rel_pathlist
2940  *        Build access paths for a base relation
2941  *
2942  * This function was copied and edited from set_rel_pathlist() in
2943  * src/backend/optimizer/path/allpaths.c
2944  */
2945 static void
2946 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2947                                  Index rti, RangeTblEntry *rte)
2948 {
2949 #if PG_VERSION_NUM >= 90200
2950         if (IS_DUMMY_REL(rel))
2951         {
2952                 /* We already proved the relation empty, so nothing more to do */
2953         }
2954         else if (rte->inh)
2955 #else
2956         if (rte->inh)
2957 #endif
2958         {
2959                 /* It's an "append relation", process accordingly */
2960                 set_append_rel_pathlist(root, rel, rti, rte);
2961         }
2962         else
2963         {
2964                 if (rel->rtekind == RTE_RELATION)
2965                 {
2966                         if (rte->relkind == RELKIND_RELATION)
2967                         {
2968                                 /* Plain relation */
2969                                 set_plain_rel_pathlist(root, rel, rte);
2970                         }
2971                         else
2972                                 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2973                 }
2974                 else
2975                         elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2976         }
2977 }
2978
2979 #define standard_join_search pg_hint_plan_standard_join_search
2980 #define join_search_one_level pg_hint_plan_join_search_one_level
2981 #define make_join_rel make_join_rel_wrapper
2982 #include "core.c"
2983
2984 #undef make_join_rel
2985 #define make_join_rel pg_hint_plan_make_join_rel
2986 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
2987 #include "make_join_rel.c"