OSDN Git Service

Clarify functionality of function parse_quote_value by renaming.
[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 (*HintDescFunction) (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         HintDescFunction        desc_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 ScanMethodHintDesc(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 JoinMethodHintDesc(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 LeadingHintDesc(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 SetHintDesc(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 quote_value(StringInfo buf, const char *value);
332
333 static const char *parse_quoted_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.desc_func = (HintDescFunction) ScanMethodHintDesc;
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.desc_func = (HintDescFunction) JoinMethodHintDesc;
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.desc_func = (HintDescFunction) LeadingHintDesc;
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.desc_func = (HintDescFunction) SetHintDesc;
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  * Copy given value into buf, with quoting with '"' if necessary.
695  */
696 static void
697 quote_value(StringInfo buf, const char *value)
698 {
699         bool            need_quote = false;
700         const char *str;
701
702         for (str = value; *str != '\0'; str++)
703         {
704                 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
705                 {
706                         need_quote = true;
707                         appendStringInfoCharMacro(buf, '"');
708                         break;
709                 }
710         }
711
712         for (str = value; *str != '\0'; str++)
713         {
714                 if (*str == '"')
715                         appendStringInfoCharMacro(buf, '"');
716
717                 appendStringInfoCharMacro(buf, *str);
718         }
719
720         if (need_quote)
721                 appendStringInfoCharMacro(buf, '"');
722 }
723
724 static void
725 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
726 {
727         ListCell   *l;
728
729         appendStringInfo(buf, "%s(", hint->base.keyword);
730         if (hint->relname != NULL)
731         {
732                 quote_value(buf, hint->relname);
733                 foreach(l, hint->indexnames)
734                 {
735                         appendStringInfoCharMacro(buf, ' ');
736                         quote_value(buf, (char *) lfirst(l));
737                 }
738         }
739         appendStringInfoString(buf, ")\n");
740 }
741
742 static void
743 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
744 {
745         int     i;
746
747         appendStringInfo(buf, "%s(", hint->base.keyword);
748         if (hint->relnames != NULL)
749         {
750                 quote_value(buf, hint->relnames[0]);
751                 for (i = 1; i < hint->nrels; i++)
752                 {
753                         appendStringInfoCharMacro(buf, ' ');
754                         quote_value(buf, hint->relnames[i]);
755                 }
756         }
757         appendStringInfoString(buf, ")\n");
758
759 }
760
761 static void
762 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
763 {
764         if (outer_inner->relation == NULL)
765         {
766                 bool            is_first;
767                 ListCell   *l;
768
769                 is_first = true;
770
771                 appendStringInfoCharMacro(buf, '(');
772                 foreach(l, outer_inner->outer_inner_pair)
773                 {
774                         if (is_first)
775                                 is_first = false;
776                         else
777                                 appendStringInfoCharMacro(buf, ' ');
778
779                         OuterInnerDesc(lfirst(l), buf);
780                 }
781
782                 appendStringInfoCharMacro(buf, ')');
783         }
784         else
785                 quote_value(buf, outer_inner->relation);
786 }
787
788 static void
789 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
790 {
791         bool            is_first;
792         ListCell   *l;
793
794         appendStringInfo(buf, "%s(", HINT_LEADING);
795         is_first = true;
796         if (hint->outer_inner == NULL)
797         {
798                 foreach(l, hint->relations)
799                 {
800                         if (is_first)
801                                 is_first = false;
802                         else
803                                 appendStringInfoCharMacro(buf, ' ');
804
805                         quote_value(buf, (char *) lfirst(l));
806                 }
807         }
808         else
809                 OuterInnerDesc(hint->outer_inner, buf);
810
811         appendStringInfoString(buf, ")\n");
812 }
813
814 static void
815 SetHintDesc(SetHint *hint, StringInfo buf)
816 {
817         bool            is_first = true;
818         ListCell   *l;
819
820         appendStringInfo(buf, "%s(", HINT_SET);
821         foreach(l, hint->words)
822         {
823                 if (is_first)
824                         is_first = false;
825                 else
826                         appendStringInfoCharMacro(buf, ' ');
827
828                 quote_value(buf, (char *) lfirst(l));
829         }
830         appendStringInfo(buf, ")\n");
831 }
832
833 /*
834  * Append string which repserents all hints in a given state to buf, with
835  * preceding title with them.
836  */
837 static void
838 desc_hint_in_state(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]->desc_func(hstate->all_hints[i], buf);
850         }
851 }
852
853 /*
854  * Dump contents of given hstate to server log with log level LOG.
855  */
856 static void
857 HintStateDump(HintState *hstate)
858 {
859         StringInfoData  buf;
860
861         if (!hstate)
862         {
863                 elog(LOG, "pg_hint_plan:\nno hint");
864                 return;
865         }
866
867         initStringInfo(&buf);
868
869         appendStringInfoString(&buf, "pg_hint_plan:\n");
870         desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
871         desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
872         desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
873         desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
874
875         elog(LOG, "%s", buf.data);
876
877         pfree(buf.data);
878 }
879
880 /*
881  * compare functions
882  */
883
884 static int
885 RelnameCmp(const void *a, const void *b)
886 {
887         const char *relnamea = *((const char **) a);
888         const char *relnameb = *((const char **) b);
889
890         return strcmp(relnamea, relnameb);
891 }
892
893 static int
894 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
895 {
896         return RelnameCmp(&a->relname, &b->relname);
897 }
898
899 static int
900 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
901 {
902         int     i;
903
904         if (a->nrels != b->nrels)
905                 return a->nrels - b->nrels;
906
907         for (i = 0; i < a->nrels; i++)
908         {
909                 int     result;
910                 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
911                         return result;
912         }
913
914         return 0;
915 }
916
917 static int
918 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
919 {
920         return 0;
921 }
922
923 static int
924 SetHintCmp(const SetHint *a, const SetHint *b)
925 {
926         return strcmp(a->name, b->name);
927 }
928
929 static int
930 HintCmp(const void *a, const void *b)
931 {
932         const Hint *hinta = *((const Hint **) a);
933         const Hint *hintb = *((const Hint **) b);
934
935         if (hinta->type != hintb->type)
936                 return hinta->type - hintb->type;
937         if (hinta->state == HINT_STATE_ERROR)
938                 return -1;
939         if (hintb->state == HINT_STATE_ERROR)
940                 return 1;
941         return hinta->cmp_func(hinta, hintb);
942 }
943
944 /*
945  * Returns byte offset of hint b from hint a.  If hint a was specified before
946  * b, positive value is returned.
947  */
948 static int
949 HintCmpWithPos(const void *a, const void *b)
950 {
951         const Hint *hinta = *((const Hint **) a);
952         const Hint *hintb = *((const Hint **) b);
953         int             result;
954
955         result = HintCmp(a, b);
956         if (result == 0)
957                 result = hinta->hint_str - hintb->hint_str;
958
959         return result;
960 }
961
962 /*
963  * parse functions
964  */
965 static const char *
966 parse_keyword(const char *str, StringInfo buf)
967 {
968         skip_space(str);
969
970         while (!isspace(*str) && *str != '(' && *str != '\0')
971                 appendStringInfoCharMacro(buf, *str++);
972
973         return str;
974 }
975
976 static const char *
977 skip_parenthesis(const char *str, char parenthesis)
978 {
979         skip_space(str);
980
981         if (*str != parenthesis)
982         {
983                 if (parenthesis == '(')
984                         hint_ereport(str, ("Opening parenthesis is necessary."));
985                 else if (parenthesis == ')')
986                         hint_ereport(str, ("Closing parenthesis is necessary."));
987
988                 return NULL;
989         }
990
991         str++;
992
993         return str;
994 }
995
996 /*
997  * Parse a token from str, and store malloc'd copy into word.  A token can be
998  * quoted with '"'.  Return value is pointer to unparsed portion of original
999  * string, or NULL if an error occurred.
1000  *
1001  * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1002  */
1003 static const char *
1004 parse_quoted_value(const char *str, char **word, bool truncate)
1005 {
1006         return parse_quoted_value_term_char(str, word, truncate, '\0');
1007 }
1008
1009 /*
1010  * In term_char, We specified the special character which a terminal of a word.
1011  * When we do not have a special character, We specified '\0'.
1012  */
1013 static const char *
1014 parse_quoted_value_term_char(const char *str, char **word, bool truncate,
1015                                                         char term_char)
1016 {
1017         StringInfoData  buf;
1018         bool                    in_quote;
1019
1020         /* Skip leading spaces. */
1021         skip_space(str);
1022
1023         initStringInfo(&buf);
1024         if (*str == '"')
1025         {
1026                 str++;
1027                 in_quote = true;
1028         }
1029         else
1030                 in_quote = false;
1031
1032         while (true)
1033         {
1034                 if (in_quote)
1035                 {
1036                         /* Double quotation must be closed. */
1037                         if (*str == '\0')
1038                         {
1039                                 pfree(buf.data);
1040                                 hint_ereport(str, ("Unterminated quoted string."));
1041                                 return NULL;
1042                         }
1043
1044                         /*
1045                          * Skip escaped double quotation.
1046                          *
1047                          * We don't allow slash-asterisk and asterisk-slash (delimiters of
1048                          * block comments) to be an object name, so users must specify
1049                          * alias for such object names.
1050                          *
1051                          * Those special names can be allowed if we care escaped slashes
1052                          * and asterisks, but we don't.
1053                          */
1054                         if (*str == '"')
1055                         {
1056                                 str++;
1057                                 if (*str != '"')
1058                                         break;
1059                         }
1060                 }
1061                 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0' ||
1062                                  *str == term_char)
1063                         break;
1064
1065                 appendStringInfoCharMacro(&buf, *str++);
1066         }
1067
1068         if (buf.len == 0)
1069         {
1070                 hint_ereport(str, ("Zero-length delimited string."));
1071
1072                 pfree(buf.data);
1073
1074                 return NULL;
1075         }
1076
1077         /* Truncate name if it's too long */
1078         if (truncate)
1079                 truncate_identifier(buf.data, strlen(buf.data), true);
1080
1081         *word = buf.data;
1082
1083         return str;
1084 }
1085
1086 static OuterInnerRels *
1087 OuterInnerRelsCreate(OuterInnerRels *outer_inner, char *name, List *outer_inner_list)
1088 {
1089         outer_inner = palloc(sizeof(OuterInnerRels));
1090         outer_inner->relation = name;
1091         outer_inner->outer_inner_pair = outer_inner_list;
1092
1093         return outer_inner;
1094 }
1095
1096 static const char *
1097 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1098 {
1099         char   *name;
1100         bool    truncate = true;
1101
1102         OuterInnerRels *outer_inner_rels;
1103         outer_inner_rels = NULL;
1104
1105         skip_space(str);
1106
1107         /* Store words in parentheses into outer_inner_list. */
1108         while(*str != ')' && *str != '\0')
1109         {
1110                 if (*str == '(')
1111                 {
1112                         str++;
1113                         outer_inner_rels = OuterInnerRelsCreate(outer_inner_rels,
1114                                                                                                         NULL,
1115                                                                                                         NIL);
1116                         str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1117                 }
1118                 else if ((str = parse_quoted_value_term_char(str, &name, truncate, '(')) == NULL)
1119                 {
1120                         list_free((*outer_inner)->outer_inner_pair);
1121                         return NULL;
1122                 }
1123                 else
1124                         outer_inner_rels = OuterInnerRelsCreate(outer_inner_rels, name, NIL);
1125
1126                 (*outer_inner)->outer_inner_pair = lappend(
1127                                                                                         (*outer_inner)->outer_inner_pair,
1128                                                                                          outer_inner_rels);
1129                 skip_space(str);
1130         }
1131
1132         str++;
1133
1134         return str;
1135 }
1136
1137 static const char *
1138 parse_parentheses_Leading(const char *str, List **name_list,
1139         OuterInnerRels **outer_inner)
1140 {
1141         char   *name;
1142         bool    truncate = true;
1143
1144         if ((str = skip_parenthesis(str, '(')) == NULL)
1145                 return NULL;
1146
1147         skip_space(str);
1148         if (*str =='(')
1149         {
1150                 str++;
1151
1152                 *outer_inner = OuterInnerRelsCreate(*outer_inner, NULL, NIL);
1153                 str = parse_parentheses_Leading_in(str, outer_inner);
1154         }
1155         else
1156         {
1157                 /* Store words in parentheses into name_list. */
1158                 while(*str != ')' && *str != '\0')
1159                 {
1160                         if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1161                         {
1162                                 list_free(*name_list);
1163                                 return NULL;
1164                         }
1165
1166                         *name_list = lappend(*name_list, name);
1167                         skip_space(str);
1168                 }
1169         }
1170
1171         if ((str = skip_parenthesis(str, ')')) == NULL)
1172                 return NULL;
1173         return str;
1174 }
1175
1176 static const char *
1177 parse_parentheses(const char *str, List **name_list, HintType type)
1178 {
1179         char   *name;
1180         bool    truncate = true;
1181
1182         if ((str = skip_parenthesis(str, '(')) == NULL)
1183                 return NULL;
1184
1185         skip_space(str);
1186
1187         /* Store words in parentheses into name_list. */
1188         while(*str != ')' && *str != '\0')
1189         {
1190                 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1191                 {
1192                         list_free(*name_list);
1193                         return NULL;
1194                 }
1195
1196                 *name_list = lappend(*name_list, name);
1197                 skip_space(str);
1198
1199                 if (type == HINT_TYPE_SET)
1200                 {
1201                         truncate = false;
1202                 }
1203         }
1204
1205         if ((str = skip_parenthesis(str, ')')) == NULL)
1206                 return NULL;
1207         return str;
1208 }
1209
1210 static void
1211 parse_hints(HintState *hstate, Query *parse, const char *str)
1212 {
1213         StringInfoData  buf;
1214         char               *head;
1215
1216         initStringInfo(&buf);
1217         while (*str != '\0')
1218         {
1219                 const HintParser *parser;
1220
1221                 /* in error message, we output the comment including the keyword. */
1222                 head = (char *) str;
1223
1224                 /* parse only the keyword of the hint. */
1225                 resetStringInfo(&buf);
1226                 str = parse_keyword(str, &buf);
1227
1228                 for (parser = parsers; parser->keyword != NULL; parser++)
1229                 {
1230                         char   *keyword = parser->keyword;
1231                         Hint   *hint;
1232
1233                         if (strcasecmp(buf.data, keyword) != 0)
1234                                 continue;
1235
1236                         hint = parser->create_func(head, keyword, parser->hint_keyword);
1237
1238                         /* parser of each hint does parse in a parenthesis. */
1239                         if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1240                         {
1241                                 hint->delete_func(hint);
1242                                 pfree(buf.data);
1243                                 return;
1244                         }
1245
1246                         /*
1247                          * Add hint information into all_hints array.  If we don't have
1248                          * enough space, double the array.
1249                          */
1250                         if (hstate->nall_hints == 0)
1251                         {
1252                                 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1253                                 hstate->all_hints = (Hint **)
1254                                         palloc(sizeof(Hint *) * hstate->max_all_hints);
1255                         }
1256                         else if (hstate->nall_hints == hstate->max_all_hints)
1257                         {
1258                                 hstate->max_all_hints *= 2;
1259                                 hstate->all_hints = (Hint **)
1260                                         repalloc(hstate->all_hints,
1261                                                          sizeof(Hint *) * hstate->max_all_hints);
1262                         }
1263
1264                         hstate->all_hints[hstate->nall_hints] = hint;
1265                         hstate->nall_hints++;
1266
1267                         skip_space(str);
1268
1269                         break;
1270                 }
1271
1272                 if (parser->keyword == NULL)
1273                 {
1274                         hint_ereport(head,
1275                                                  ("Unrecognized hint keyword \"%s\".", buf.data));
1276                         pfree(buf.data);
1277                         return;
1278                 }
1279         }
1280
1281         pfree(buf.data);
1282 }
1283
1284 /*
1285  * Do basic parsing of the query head comment.
1286  */
1287 static HintState *
1288 parse_head_comment(Query *parse)
1289 {
1290         const char *p;
1291         char       *head;
1292         char       *tail;
1293         int                     len;
1294         int                     i;
1295         HintState   *hstate;
1296
1297         /* get client-supplied query string. */
1298         if (stmt_name)
1299         {
1300                 PreparedStatement  *entry;
1301
1302                 entry = FetchPreparedStatement(stmt_name, true);
1303                 p = entry->plansource->query_string;
1304         }
1305         else
1306                 p = debug_query_string;
1307
1308         if (p == NULL)
1309                 return NULL;
1310
1311         /* extract query head comment. */
1312         len = strlen(HINT_START);
1313         skip_space(p);
1314         if (strncmp(p, HINT_START, len))
1315                 return NULL;
1316
1317         head = (char *) p;
1318         p += len;
1319         skip_space(p);
1320
1321         /* find hint end keyword. */
1322         if ((tail = strstr(p, HINT_END)) == NULL)
1323         {
1324                 hint_ereport(head, ("Unterminated block comment."));
1325                 return NULL;
1326         }
1327
1328         /* We don't support nested block comments. */
1329         if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1330         {
1331                 hint_ereport(head, ("Nested block comments are not supported."));
1332                 return NULL;
1333         }
1334
1335         /* Make a copy of hint. */
1336         len = tail - p;
1337         head = palloc(len + 1);
1338         memcpy(head, p, len);
1339         head[len] = '\0';
1340         p = head;
1341
1342         hstate = HintStateCreate();
1343         hstate->hint_str = head;
1344
1345         /* parse each hint. */
1346         parse_hints(hstate, parse, p);
1347
1348         /* When nothing specified a hint, we free HintState and returns NULL. */
1349         if (hstate->nall_hints == 0)
1350         {
1351                 HintStateDelete(hstate);
1352                 return NULL;
1353         }
1354
1355         /* Sort hints in order of original position. */
1356         qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1357                   HintCmpWithPos);
1358
1359         /* Count number of hints per hint-type. */
1360         for (i = 0; i < hstate->nall_hints; i++)
1361         {
1362                 Hint   *cur_hint = hstate->all_hints[i];
1363                 hstate->num_hints[cur_hint->type]++;
1364         }
1365
1366         /*
1367          * If an object (or a set of objects) has multiple hints of same hint-type,
1368          * only the last hint is valid and others are igonred in planning.
1369          * Hints except the last are marked as 'duplicated' to remember the order.
1370          */
1371         for (i = 0; i < hstate->nall_hints - 1; i++)
1372         {
1373                 Hint   *cur_hint = hstate->all_hints[i];
1374                 Hint   *next_hint = hstate->all_hints[i + 1];
1375
1376                 /*
1377                  *  TODO : Leadingヒントの重複チェックは、transform_join_hints関数の実行
1378                  *       中に実施する。
1379                 */
1380                 if (i >= hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1381                             hstate->num_hints[HINT_TYPE_JOIN_METHOD] &&
1382                         i < hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1383                                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1384                                 hstate->num_hints[HINT_TYPE_LEADING])
1385                         continue;
1386
1387                 /*
1388                  * Note that we need to pass addresses of hint pointers, because
1389                  * HintCmp is designed to sort array of Hint* by qsort.
1390                  */
1391                 if (HintCmp(&cur_hint, &next_hint) == 0)
1392                 {
1393                         hint_ereport(cur_hint->hint_str,
1394                                                  ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1395                         cur_hint->state = HINT_STATE_DUPLICATION;
1396                 }
1397         }
1398
1399         /*
1400          * Make sure that per-type array pointers point proper position in the
1401          * array which consists of all hints.
1402          */
1403         hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1404         hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1405                 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1406         hstate->leading_hint = (LeadingHint **) hstate->all_hints +
1407                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1408                 hstate->num_hints[HINT_TYPE_JOIN_METHOD];
1409         hstate->set_hints = (SetHint **) hstate->all_hints +
1410                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1411                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1412                 hstate->num_hints[HINT_TYPE_LEADING];
1413
1414         return hstate;
1415 }
1416
1417 /*
1418  * Parse inside of parentheses of scan-method hints.
1419  */
1420 static const char *
1421 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1422                                         const char *str)
1423 {
1424         const char         *keyword = hint->base.keyword;
1425         HintKeyword             hint_keyword = hint->base.hint_keyword;
1426         List               *name_list = NIL;
1427         int                             length;
1428
1429         if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1430                 return NULL;
1431
1432         /* Parse relation name and index name(s) if given hint accepts. */
1433         length = list_length(name_list);
1434         if (length > 0)
1435         {
1436                 hint->relname = linitial(name_list);
1437                 hint->indexnames = list_delete_first(name_list);
1438
1439                 /* check whether the hint accepts index name(s). */
1440                 if (hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1441 #if PG_VERSION_NUM >= 90200
1442                         hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1443 #endif
1444                         hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1445                         length != 1)
1446                 {
1447                         hint_ereport(str,
1448                                                  ("%s hint accepts only one relation.",
1449                                                   hint->base.keyword));
1450                         hint->base.state = HINT_STATE_ERROR;
1451                         return str;
1452                 }
1453         }
1454         else
1455         {
1456                 hint_ereport(str,
1457                                          ("%s hint requires a relation.",
1458                                           hint->base.keyword));
1459                 hint->base.state = HINT_STATE_ERROR;
1460                 return str;
1461         }
1462
1463         /* Set a bit for specified hint. */
1464         switch (hint_keyword)
1465         {
1466                 case HINT_KEYWORD_SEQSCAN:
1467                         hint->enforce_mask = ENABLE_SEQSCAN;
1468                         break;
1469                 case HINT_KEYWORD_INDEXSCAN:
1470                         hint->enforce_mask = ENABLE_INDEXSCAN;
1471                         break;
1472                 case HINT_KEYWORD_BITMAPSCAN:
1473                         hint->enforce_mask = ENABLE_BITMAPSCAN;
1474                         break;
1475                 case HINT_KEYWORD_TIDSCAN:
1476                         hint->enforce_mask = ENABLE_TIDSCAN;
1477                         break;
1478                 case HINT_KEYWORD_NOSEQSCAN:
1479                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1480                         break;
1481                 case HINT_KEYWORD_NOINDEXSCAN:
1482                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1483                         break;
1484                 case HINT_KEYWORD_NOBITMAPSCAN:
1485                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1486                         break;
1487                 case HINT_KEYWORD_NOTIDSCAN:
1488                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1489                         break;
1490 #if PG_VERSION_NUM >= 90200
1491                 case HINT_KEYWORD_INDEXONLYSCAN:
1492                         hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1493                         break;
1494                 case HINT_KEYWORD_NOINDEXONLYSCAN:
1495                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1496                         break;
1497 #endif
1498                 default:
1499                         hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1500                         return NULL;
1501                         break;
1502         }
1503
1504         return str;
1505 }
1506
1507 static const char *
1508 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1509                                         const char *str)
1510 {
1511         const char         *keyword = hint->base.keyword;
1512         HintKeyword             hint_keyword = hint->base.hint_keyword;
1513         List               *name_list = NIL;
1514
1515         if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1516                 return NULL;
1517
1518         hint->nrels = list_length(name_list);
1519
1520         if (hint->nrels > 0)
1521         {
1522                 ListCell   *l;
1523                 int                     i = 0;
1524
1525                 /*
1526                  * Transform relation names from list to array to sort them with qsort
1527                  * after.
1528                  */
1529                 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1530                 foreach (l, name_list)
1531                 {
1532                         hint->relnames[i] = lfirst(l);
1533                         i++;
1534                 }
1535         }
1536
1537         list_free(name_list);
1538
1539         /* A join hint requires at least two relations */
1540         if (hint->nrels < 2)
1541         {
1542                 hint_ereport(str,
1543                                          ("%s hint requires at least two relations.",
1544                                           hint->base.keyword));
1545                 hint->base.state = HINT_STATE_ERROR;
1546                 return str;
1547         }
1548
1549         /* Sort hints in alphabetical order of relation names. */
1550         qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1551
1552         switch (hint_keyword)
1553         {
1554                 case HINT_KEYWORD_NESTLOOP:
1555                         hint->enforce_mask = ENABLE_NESTLOOP;
1556                         break;
1557                 case HINT_KEYWORD_MERGEJOIN:
1558                         hint->enforce_mask = ENABLE_MERGEJOIN;
1559                         break;
1560                 case HINT_KEYWORD_HASHJOIN:
1561                         hint->enforce_mask = ENABLE_HASHJOIN;
1562                         break;
1563                 case HINT_KEYWORD_NONESTLOOP:
1564                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1565                         break;
1566                 case HINT_KEYWORD_NOMERGEJOIN:
1567                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1568                         break;
1569                 case HINT_KEYWORD_NOHASHJOIN:
1570                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1571                         break;
1572                 default:
1573                         hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1574                         return NULL;
1575                         break;
1576         }
1577
1578         return str;
1579 }
1580
1581 static bool
1582 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1583 {
1584         ListCell *l;
1585         if (outer_inner->outer_inner_pair == NIL)
1586         {
1587                 if (outer_inner->relation)
1588                         return true;
1589                 else
1590                         return false;
1591         }
1592
1593         if (list_length(outer_inner->outer_inner_pair) == 2)
1594         {
1595                 foreach(l, outer_inner->outer_inner_pair)
1596                 {
1597                         if (!OuterInnerPairCheck(lfirst(l)))
1598                                 return false;
1599                 }
1600         }
1601         else
1602                 return false;
1603
1604         return true;
1605 }
1606
1607 static const char *
1608 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1609                                  const char *str)
1610 {
1611         List               *name_list = NIL;
1612         OuterInnerRels *outer_inner = NULL;
1613
1614         if ((str =
1615                  parse_parentheses_Leading(str, &name_list, &outer_inner)) == NULL)
1616                 return NULL;
1617
1618         hint->relations = name_list;
1619         hint->outer_inner = outer_inner;
1620
1621         /* A Leading hint requires at least two relations */
1622         if (list_length(hint->relations) < 2 && hint->outer_inner == NULL)
1623         {
1624                 hint_ereport(hint->base.hint_str,
1625                                          ("%s hint requires at least two relations.",
1626                                           HINT_LEADING));
1627                 hint->base.state = HINT_STATE_ERROR;
1628         }
1629         else if (hint->outer_inner != NULL &&
1630                          !OuterInnerPairCheck(hint->outer_inner))
1631         {
1632                 hint_ereport(hint->base.hint_str,
1633                                          ("%s hint requires two sets of relations when parentheses nests.",
1634                                           HINT_LEADING));
1635                 hint->base.state = HINT_STATE_ERROR;
1636         }
1637
1638         return str;
1639 }
1640
1641 static const char *
1642 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1643 {
1644         List   *name_list = NIL;
1645
1646         if ((str = parse_parentheses(str, &name_list, hint->base.type)) == NULL)
1647                 return NULL;
1648
1649         hint->words = name_list;
1650
1651         /* We need both name and value to set GUC parameter. */
1652         if (list_length(name_list) == 2)
1653         {
1654                 hint->name = linitial(name_list);
1655                 hint->value = lsecond(name_list);
1656         }
1657         else
1658         {
1659                 hint_ereport(hint->base.hint_str,
1660                                          ("%s hint requires name and value of GUC parameter.",
1661                                           HINT_SET));
1662                 hint->base.state = HINT_STATE_ERROR;
1663         }
1664
1665         return str;
1666 }
1667
1668 /*
1669  * set GUC parameter functions
1670  */
1671
1672 static int
1673 set_config_option_wrapper(const char *name, const char *value,
1674                                                   GucContext context, GucSource source,
1675                                                   GucAction action, bool changeVal, int elevel)
1676 {
1677         int                             result = 0;
1678         MemoryContext   ccxt = CurrentMemoryContext;
1679
1680         PG_TRY();
1681         {
1682 #if PG_VERSION_NUM >= 90200
1683                 result = set_config_option(name, value, context, source,
1684                                                                    action, changeVal, 0);
1685 #else
1686                 result = set_config_option(name, value, context, source,
1687                                                                    action, changeVal);
1688 #endif
1689         }
1690         PG_CATCH();
1691         {
1692                 ErrorData          *errdata;
1693
1694                 /* Save error info */
1695                 MemoryContextSwitchTo(ccxt);
1696                 errdata = CopyErrorData();
1697                 FlushErrorState();
1698
1699                 ereport(elevel, (errcode(errdata->sqlerrcode),
1700                                 errmsg("%s", errdata->message),
1701                                 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1702                                 errdata->hint ? errhint("%s", errdata->hint) : 0));
1703                 FreeErrorData(errdata);
1704         }
1705         PG_END_TRY();
1706
1707         return result;
1708 }
1709
1710 static int
1711 set_config_options(SetHint **options, int noptions, GucContext context)
1712 {
1713         int     i;
1714         int     save_nestlevel;
1715
1716         save_nestlevel = NewGUCNestLevel();
1717
1718         for (i = 0; i < noptions; i++)
1719         {
1720                 SetHint    *hint = options[i];
1721                 int                     result;
1722
1723                 if (!hint_state_enabled(hint))
1724                         continue;
1725
1726                 result = set_config_option_wrapper(hint->name, hint->value, context,
1727                                                                                    PGC_S_SESSION, GUC_ACTION_SAVE, true,
1728                                                                                    pg_hint_plan_parse_messages);
1729                 if (result != 0)
1730                         hint->base.state = HINT_STATE_USED;
1731                 else
1732                         hint->base.state = HINT_STATE_ERROR;
1733         }
1734
1735         return save_nestlevel;
1736 }
1737
1738 #define SET_CONFIG_OPTION(name, type_bits) \
1739         set_config_option_wrapper((name), \
1740                 (mask & (type_bits)) ? "true" : "false", \
1741                 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1742
1743 static void
1744 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1745 {
1746         unsigned char   mask;
1747
1748         if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1749                 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1750 #if PG_VERSION_NUM >= 90200
1751                 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1752 #endif
1753                 )
1754                 mask = enforce_mask;
1755         else
1756                 mask = enforce_mask & current_hint->init_scan_mask;
1757
1758         SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1759         SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1760         SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1761         SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1762 #if PG_VERSION_NUM >= 90200
1763         SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1764 #endif
1765 }
1766
1767 static void
1768 set_join_config_options(unsigned char enforce_mask, GucContext context)
1769 {
1770         unsigned char   mask;
1771
1772         if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1773                 enforce_mask == ENABLE_HASHJOIN)
1774                 mask = enforce_mask;
1775         else
1776                 mask = enforce_mask & current_hint->init_join_mask;
1777
1778         SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1779         SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1780         SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1781 }
1782
1783 /*
1784  * pg_hint_plan hook functions
1785  */
1786
1787 static void
1788 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1789                                                         ParamListInfo params, bool isTopLevel,
1790                                                         DestReceiver *dest, char *completionTag)
1791 {
1792         Node                               *node;
1793
1794         if (!pg_hint_plan_enable_hint)
1795         {
1796                 if (prev_ProcessUtility)
1797                         (*prev_ProcessUtility) (parsetree, queryString, params,
1798                                                                         isTopLevel, dest, completionTag);
1799                 else
1800                         standard_ProcessUtility(parsetree, queryString, params,
1801                                                                         isTopLevel, dest, completionTag);
1802
1803                 return;
1804         }
1805
1806         node = parsetree;
1807         if (IsA(node, ExplainStmt))
1808         {
1809                 /*
1810                  * Draw out parse tree of actual query from Query struct of EXPLAIN
1811                  * statement.
1812                  */
1813                 ExplainStmt        *stmt;
1814                 Query              *query;
1815
1816                 stmt = (ExplainStmt *) node;
1817
1818                 Assert(IsA(stmt->query, Query));
1819                 query = (Query *) stmt->query;
1820
1821                 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1822                         node = query->utilityStmt;
1823         }
1824
1825         /*
1826          * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1827          * specified to preceding PREPARE command to use it as source of hints.
1828          */
1829         if (IsA(node, ExecuteStmt))
1830         {
1831                 ExecuteStmt        *stmt;
1832
1833                 stmt = (ExecuteStmt *) node;
1834                 stmt_name = stmt->name;
1835         }
1836 #if PG_VERSION_NUM >= 90200
1837         /*
1838          * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1839          * specially here.
1840          */
1841         if (IsA(node, CreateTableAsStmt))
1842         {
1843                 CreateTableAsStmt          *stmt;
1844                 Query              *query;
1845
1846                 stmt = (CreateTableAsStmt *) node;
1847                 Assert(IsA(stmt->query, Query));
1848                 query = (Query *) stmt->query;
1849
1850                 if (query->commandType == CMD_UTILITY &&
1851                         IsA(query->utilityStmt, ExecuteStmt))
1852                 {
1853                         ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1854                         stmt_name = estmt->name;
1855                 }
1856         }
1857 #endif
1858         if (stmt_name)
1859         {
1860                 PG_TRY();
1861                 {
1862                         if (prev_ProcessUtility)
1863                                 (*prev_ProcessUtility) (parsetree, queryString, params,
1864                                                                                 isTopLevel, dest, completionTag);
1865                         else
1866                                 standard_ProcessUtility(parsetree, queryString, params,
1867                                                                                 isTopLevel, dest, completionTag);
1868                 }
1869                 PG_CATCH();
1870                 {
1871                         stmt_name = NULL;
1872                         PG_RE_THROW();
1873                 }
1874                 PG_END_TRY();
1875
1876                 stmt_name = NULL;
1877
1878                 return;
1879         }
1880
1881         if (prev_ProcessUtility)
1882                 (*prev_ProcessUtility) (parsetree, queryString, params,
1883                                                                 isTopLevel, dest, completionTag);
1884         else
1885                 standard_ProcessUtility(parsetree, queryString, params,
1886                                                                 isTopLevel, dest, completionTag);
1887 }
1888
1889 /*
1890  * Push a hint into hint stack which is implemented with List struct.  Head of
1891  * list is top of stack.
1892  */
1893 static void
1894 push_hint(HintState *hstate)
1895 {
1896         /* Prepend new hint to the list means pushing to stack. */
1897         HintStateStack = lcons(hstate, HintStateStack);
1898
1899         /* Pushed hint is the one which should be used hereafter. */
1900         current_hint = hstate;
1901 }
1902
1903 /* Pop a hint from hint stack.  Popped hint is automatically discarded. */
1904 static void
1905 pop_hint(void)
1906 {
1907         /* Hint stack must not be empty. */
1908         if(HintStateStack == NIL)
1909                 elog(ERROR, "hint stack is empty");
1910
1911         /*
1912          * Take a hint at the head from the list, and free it.  Switch current_hint
1913          * to point new head (NULL if the list is empty).
1914          */
1915         HintStateStack = list_delete_first(HintStateStack);
1916         HintStateDelete(current_hint);
1917         if(HintStateStack == NIL)
1918                 current_hint = NULL;
1919         else
1920                 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1921 }
1922
1923 static PlannedStmt *
1924 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1925 {
1926         int                             save_nestlevel;
1927         PlannedStmt        *result;
1928         HintState          *hstate;
1929
1930         /*
1931          * Use standard planner if pg_hint_plan is disabled.  Other hook functions
1932          * try to change plan with current_hint if any, so set it to NULL.
1933          */
1934         if (!pg_hint_plan_enable_hint)
1935         {
1936                 current_hint = NULL;
1937
1938                 if (prev_planner)
1939                         return (*prev_planner) (parse, cursorOptions, boundParams);
1940                 else
1941                         return standard_planner(parse, cursorOptions, boundParams);
1942         }
1943
1944         /* Create hint struct from parse tree. */
1945         hstate = parse_head_comment(parse);
1946
1947         /*
1948          * Use standard planner if the statement has not valid hint.  Other hook
1949          * functions try to change plan with current_hint if any, so set it to
1950          * NULL.
1951          */
1952         if (!hstate)
1953         {
1954                 current_hint = NULL;
1955
1956                 if (prev_planner)
1957                         return (*prev_planner) (parse, cursorOptions, boundParams);
1958                 else
1959                         return standard_planner(parse, cursorOptions, boundParams);
1960         }
1961
1962         /*
1963          * Push new hint struct to the hint stack to disable previous hint context.
1964          */
1965         push_hint(hstate);
1966
1967         /* Set GUC parameters which are specified with Set hint. */
1968         save_nestlevel = set_config_options(current_hint->set_hints,
1969                                                                                 current_hint->num_hints[HINT_TYPE_SET],
1970                                                                                 current_hint->context);
1971
1972         if (enable_seqscan)
1973                 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1974         if (enable_indexscan)
1975                 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1976         if (enable_bitmapscan)
1977                 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1978         if (enable_tidscan)
1979                 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1980 #if PG_VERSION_NUM >= 90200
1981         if (enable_indexonlyscan)
1982                 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1983 #endif
1984         if (enable_nestloop)
1985                 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1986         if (enable_mergejoin)
1987                 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1988         if (enable_hashjoin)
1989                 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1990
1991         /*
1992          * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1993          * state when this planner started when error occurred in planner.
1994          */
1995         PG_TRY();
1996         {
1997                 if (prev_planner)
1998                         result = (*prev_planner) (parse, cursorOptions, boundParams);
1999                 else
2000                         result = standard_planner(parse, cursorOptions, boundParams);
2001         }
2002         PG_CATCH();
2003         {
2004                 /*
2005                  * Rollback changes of GUC parameters, and pop current hint context
2006                  * from hint stack to rewind the state.
2007                  */
2008                 AtEOXact_GUC(true, save_nestlevel);
2009                 pop_hint();
2010                 PG_RE_THROW();
2011         }
2012         PG_END_TRY();
2013
2014         /* Print hint in debug mode. */
2015         if (pg_hint_plan_debug_print)
2016                 HintStateDump(current_hint);
2017
2018         /*
2019          * Rollback changes of GUC parameters, and pop current hint context from
2020          * hint stack to rewind the state.
2021          */
2022         AtEOXact_GUC(true, save_nestlevel);
2023         pop_hint();
2024
2025         return result;
2026 }
2027
2028 /*
2029  * Return scan method hint which matches given aliasname.
2030  */
2031 static ScanMethodHint *
2032 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2033 {
2034         RangeTblEntry  *rte;
2035         int                             i;
2036
2037         /*
2038          * We can't apply scan method hint if the relation is:
2039          *   - not a base relation
2040          *   - not an ordinary relation (such as join and subquery)
2041          */
2042         if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2043                 return NULL;
2044
2045         rte = root->simple_rte_array[rel->relid];
2046
2047         /* We can't force scan method of foreign tables */
2048         if (rte->relkind == RELKIND_FOREIGN_TABLE)
2049                 return NULL;
2050
2051         /* Find scan method hint, which matches given names, from the list. */
2052         for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2053         {
2054                 ScanMethodHint *hint = current_hint->scan_hints[i];
2055
2056                 /* We ignore disabled hints. */
2057                 if (!hint_state_enabled(hint))
2058                         continue;
2059
2060                 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2061                         return hint;
2062         }
2063
2064         return NULL;
2065 }
2066
2067 static void
2068 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2069 {
2070         ListCell           *cell;
2071         ListCell           *prev;
2072         ListCell           *next;
2073         StringInfoData  buf;
2074
2075         /*
2076          * We delete all the IndexOptInfo list and prevent you from being usable by
2077          * a scan.
2078          */
2079         if (hint->enforce_mask == ENABLE_SEQSCAN ||
2080                 hint->enforce_mask == ENABLE_TIDSCAN)
2081         {
2082                 list_free_deep(rel->indexlist);
2083                 rel->indexlist = NIL;
2084                 hint->base.state = HINT_STATE_USED;
2085
2086                 return;
2087         }
2088
2089         /*
2090          * When a list of indexes is not specified, we just use all indexes.
2091          */
2092         if (hint->indexnames == NIL)
2093                 return;
2094
2095         /*
2096          * Leaving only an specified index, we delete it from a IndexOptInfo list
2097          * other than it.
2098          */
2099         prev = NULL;
2100         if (pg_hint_plan_debug_print)
2101                 initStringInfo(&buf);
2102
2103         for (cell = list_head(rel->indexlist); cell; cell = next)
2104         {
2105                 IndexOptInfo   *info = (IndexOptInfo *) lfirst(cell);
2106                 char               *indexname = get_rel_name(info->indexoid);
2107                 ListCell           *l;
2108                 bool                    use_index = false;
2109
2110                 next = lnext(cell);
2111
2112                 foreach(l, hint->indexnames)
2113                 {
2114                         if (RelnameCmp(&indexname, &lfirst(l)) == 0)
2115                         {
2116                                 use_index = true;
2117                                 if (pg_hint_plan_debug_print)
2118                                 {
2119                                         appendStringInfoCharMacro(&buf, ' ');
2120                                         quote_value(&buf, indexname);
2121                                 }
2122
2123                                 break;
2124                         }
2125                 }
2126
2127                 if (!use_index)
2128                         rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2129                 else
2130                         prev = cell;
2131
2132                 pfree(indexname);
2133         }
2134
2135         if (pg_hint_plan_debug_print)
2136         {
2137                 char   *relname;
2138                 StringInfoData  rel_buf;
2139
2140                 if (OidIsValid(relationObjectId))
2141                         relname = get_rel_name(relationObjectId);
2142                 else
2143                         relname = hint->relname;
2144
2145                 initStringInfo(&rel_buf);
2146                 quote_value(&rel_buf, relname);
2147
2148                 ereport(LOG,
2149                                 (errmsg("available indexes for %s(%s):%s",
2150                                          hint->base.keyword,
2151                                          rel_buf.data,
2152                                          buf.data)));
2153                 pfree(buf.data);
2154                 pfree(rel_buf.data);
2155         }
2156 }
2157
2158 static void
2159 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2160                                                            bool inhparent, RelOptInfo *rel)
2161 {
2162         ScanMethodHint *hint;
2163
2164         if (prev_get_relation_info)
2165                 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2166
2167         /* Do nothing if we don't have valid hint in this context. */
2168         if (!current_hint)
2169                 return;
2170
2171         if (inhparent)
2172         {
2173                 /* store does relids of parent table. */
2174                 current_hint->parent_relid = rel->relid;
2175         }
2176         else if (current_hint->parent_relid != 0)
2177         {
2178                 /*
2179                  * We use the same GUC parameter if this table is the child table of a
2180                  * table called pg_hint_plan_get_relation_info just before that.
2181                  */
2182                 ListCell   *l;
2183
2184                 /* append_rel_list contains all append rels; ignore others */
2185                 foreach(l, root->append_rel_list)
2186                 {
2187                         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2188
2189                         /* This rel is child table. */
2190                         if (appinfo->parent_relid == current_hint->parent_relid &&
2191                                 appinfo->child_relid == rel->relid)
2192                         {
2193                                 if (current_hint->parent_hint)
2194                                         delete_indexes(current_hint->parent_hint, rel,
2195                                                                    relationObjectId);
2196
2197                                 return;
2198                         }
2199                 }
2200
2201                 /* This rel is not inherit table. */
2202                 current_hint->parent_relid = 0;
2203                 current_hint->parent_hint = NULL;
2204         }
2205
2206         /*
2207          * If scan method hint was given, reset GUC parameters which control
2208          * planner behavior about choosing scan methods.
2209          */
2210         if ((hint = find_scan_hint(root, rel)) == NULL)
2211         {
2212                 set_scan_config_options(current_hint->init_scan_mask,
2213                                                                 current_hint->context);
2214                 return;
2215         }
2216         set_scan_config_options(hint->enforce_mask, current_hint->context);
2217         hint->base.state = HINT_STATE_USED;
2218         if (inhparent)
2219                 current_hint->parent_hint = hint;
2220         else
2221                 delete_indexes(hint, rel, InvalidOid);
2222 }
2223
2224 /*
2225  * Return index of relation which matches given aliasname, or 0 if not found.
2226  * If same aliasname was used multiple times in a query, return -1.
2227  */
2228 static int
2229 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2230                                          const char *str)
2231 {
2232         int             i;
2233         Index   found = 0;
2234
2235         for (i = 1; i < root->simple_rel_array_size; i++)
2236         {
2237                 ListCell   *l;
2238
2239                 if (root->simple_rel_array[i] == NULL)
2240                         continue;
2241
2242                 Assert(i == root->simple_rel_array[i]->relid);
2243
2244                 if (RelnameCmp(&aliasname,
2245                                            &root->simple_rte_array[i]->eref->aliasname) != 0)
2246                         continue;
2247
2248                 foreach(l, initial_rels)
2249                 {
2250                         RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2251
2252                         if (rel->reloptkind == RELOPT_BASEREL)
2253                         {
2254                                 if (rel->relid != i)
2255                                         continue;
2256                         }
2257                         else
2258                         {
2259                                 Assert(rel->reloptkind == RELOPT_JOINREL);
2260
2261                                 if (!bms_is_member(i, rel->relids))
2262                                         continue;
2263                         }
2264
2265                         if (found != 0)
2266                         {
2267                                 hint_ereport(str,
2268                                                          ("Relation name \"%s\" is ambiguous.",
2269                                                           aliasname));
2270                                 return -1;
2271                         }
2272
2273                         found = i;
2274                         break;
2275                 }
2276
2277         }
2278
2279         return found;
2280 }
2281
2282 /*
2283  * Return join hint which matches given joinrelids.
2284  */
2285 static JoinMethodHint *
2286 find_join_hint(Relids joinrelids)
2287 {
2288         List       *join_hint;
2289         ListCell   *l;
2290
2291         join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2292
2293         foreach(l, join_hint)
2294         {
2295                 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2296
2297                 if (bms_equal(joinrelids, hint->joinrelids))
2298                         return hint;
2299         }
2300
2301         return NULL;
2302 }
2303
2304 static List *
2305 OuterInnerList(OuterInnerRels *outer_inner)
2306 {
2307         List               *outer_inner_list = NIL;
2308         ListCell           *l;
2309         OuterInnerRels *outer_inner_rels;
2310
2311         foreach(l, outer_inner->outer_inner_pair)
2312         {
2313                 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
2314
2315                 if (outer_inner_rels->relation != NULL)
2316                         outer_inner_list = lappend(outer_inner_list,
2317                                                                            outer_inner_rels->relation);
2318                 else
2319                         outer_inner_list = list_concat(outer_inner_list,
2320                                                                                    OuterInnerList(outer_inner_rels));
2321         }
2322         return outer_inner_list;
2323 }
2324
2325 static Relids
2326 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2327         PlannerInfo *root, List *initial_rels, HintState *hstate, int *njoinrels,
2328         int nbaserel)
2329 {
2330         OuterInnerRels *outer_rels;
2331         OuterInnerRels *inner_rels;
2332         Relids                  outer_relids;
2333         Relids                  inner_relids;
2334         Relids                  join_relids;
2335         JoinMethodHint *hint;
2336
2337         if (outer_inner->relation != NULL)
2338         {
2339                 (*njoinrels)++;
2340                 return bms_make_singleton(
2341                                         find_relid_aliasname(root, outer_inner->relation,
2342                                                                                  initial_rels,
2343                                                                                  leading_hint->base.hint_str));
2344         }
2345
2346         outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2347         inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2348
2349         outer_relids = OuterInnerJoinCreate(outer_rels,
2350                                                                                 leading_hint,
2351                                                                                 root,
2352                                                                                 initial_rels,
2353                                                                                 hstate,
2354                                                                                 njoinrels,
2355                                                                                 nbaserel);
2356         inner_relids = OuterInnerJoinCreate(inner_rels,
2357                                                                                 leading_hint,
2358                                                                                 root,
2359                                                                                 initial_rels,
2360                                                                                 hstate,
2361                                                                                 njoinrels,
2362                                                                                 nbaserel);
2363
2364         join_relids = bms_add_members(outer_relids, inner_relids);
2365
2366         if (bms_num_members(join_relids) > nbaserel || *njoinrels > nbaserel)
2367                 return join_relids;
2368
2369         /*
2370          * If we don't have join method hint, create new one for the
2371          * join combination with all join methods are enabled.
2372          */
2373         hint = find_join_hint(join_relids);
2374         if (hint == NULL)
2375         {
2376                 /*
2377                  * Here relnames is not set, since Relids bitmap is sufficient to
2378                  * control paths of this query afterward.
2379                  */
2380                 hint = (JoinMethodHint *) JoinMethodHintCreate(
2381                                         leading_hint->base.hint_str,
2382                                         HINT_LEADING,
2383                                         HINT_KEYWORD_LEADING);
2384                 hint->base.state = HINT_STATE_USED;
2385                 hint->nrels = bms_num_members(join_relids);
2386                 hint->enforce_mask = ENABLE_ALL_JOIN;
2387                 hint->joinrelids = bms_copy(join_relids);
2388                 hint->inner_nrels = bms_num_members(inner_relids);
2389                 hint->inner_joinrelids = bms_copy(inner_relids);
2390
2391                 hstate->join_hint_level[hint->nrels] =
2392                         lappend(hstate->join_hint_level[hint->nrels], hint);
2393         }
2394         else
2395         {
2396                 hint->inner_nrels = bms_num_members(inner_relids);
2397                 hint->inner_joinrelids = bms_copy(inner_relids);
2398         }
2399
2400         return join_relids;
2401 }
2402
2403 /*
2404  * Transform join method hint into handy form.
2405  *
2406  *   - create bitmap of relids from alias names, to make it easier to check
2407  *     whether a join path matches a join method hint.
2408  *   - add join method hints which are necessary to enforce join order
2409  *     specified by Leading hint
2410  */
2411 static void
2412 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2413                 List *initial_rels, JoinMethodHint **join_method_hints,
2414                 LeadingHint *lhint)
2415 {
2416         int                             i;
2417         int                             relid;
2418         Relids                  joinrelids;
2419         int                             njoinrels;
2420         ListCell           *l;
2421         char               *relname;
2422         bool                    exist_effective_leading;
2423
2424         /*
2425          * Create bitmap of relids from alias names for each join method hint.
2426          * Bitmaps are more handy than strings in join searching.
2427          */
2428         for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2429         {
2430                 JoinMethodHint *hint = hstate->join_hints[i];
2431                 int     j;
2432
2433                 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2434                         continue;
2435
2436                 bms_free(hint->joinrelids);
2437                 hint->joinrelids = NULL;
2438                 relid = 0;
2439                 for (j = 0; j < hint->nrels; j++)
2440                 {
2441                         relname = hint->relnames[j];
2442
2443                         relid = find_relid_aliasname(root, relname, initial_rels,
2444                                                                                  hint->base.hint_str);
2445
2446                         if (relid == -1)
2447                                 hint->base.state = HINT_STATE_ERROR;
2448
2449                         if (relid <= 0)
2450                                 break;
2451
2452                         if (bms_is_member(relid, hint->joinrelids))
2453                         {
2454                                 hint_ereport(hint->base.hint_str,
2455                                                          ("Relation name \"%s\" is duplicated.", relname));
2456                                 hint->base.state = HINT_STATE_ERROR;
2457                                 break;
2458                         }
2459
2460                         hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2461                 }
2462
2463                 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2464                         continue;
2465
2466                 hstate->join_hint_level[hint->nrels] =
2467                         lappend(hstate->join_hint_level[hint->nrels], hint);
2468         }
2469
2470         /* Do nothing if no Leading hint was supplied. */
2471         if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2472                 return;
2473
2474         /*
2475          * Decide to use Leading hint。
2476          */
2477         exist_effective_leading = false;
2478         for (i = hstate->num_hints[HINT_TYPE_LEADING] - 1; i >= 0; i--) {
2479                 LeadingHint *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2480
2481                 List *relname_list;
2482                 Relids  relids;
2483
2484                 if (leading_hint->base.state == HINT_STATE_ERROR)
2485                         continue;
2486
2487                 if (leading_hint->outer_inner != NULL)
2488                         relname_list = OuterInnerList(leading_hint->outer_inner);
2489                 else
2490                         relname_list = leading_hint->relations;
2491
2492                 relid = 0;
2493                 relids = 0;
2494
2495                 foreach(l, relname_list)
2496                 {
2497                         relname = (char *)lfirst(l);;
2498
2499                         relid = find_relid_aliasname(root, relname, initial_rels,
2500                                                                                  leading_hint->base.hint_str);
2501                         if (relid == -1)
2502                                 leading_hint->base.state = HINT_STATE_ERROR;
2503
2504                         if (relid <= 0)
2505                                 break;
2506
2507                         if (bms_is_member(relid, relids))
2508                         {
2509                                 hint_ereport(leading_hint->base.hint_str,
2510                                                          ("Relation name \"%s\" is duplicated.", relname));
2511                                 leading_hint->base.state = HINT_STATE_ERROR;
2512                                 break;
2513                         }
2514
2515                         relids = bms_add_member(relids, relid);
2516                 }
2517
2518                 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
2519                         continue;
2520
2521                 if (exist_effective_leading)
2522                 {
2523                         hint_ereport(leading_hint->base.hint_str,
2524                                  ("Conflict %s hint.", HintTypeName[leading_hint->base.type]));
2525                         leading_hint->base.state = HINT_STATE_DUPLICATION;
2526                 }
2527                 else
2528                 {
2529                         leading_hint->base.state = HINT_STATE_USED;
2530                         exist_effective_leading = true;
2531                         lhint = leading_hint;
2532                 }
2533         }
2534         if (exist_effective_leading == false)
2535                 return;
2536
2537         /*
2538          * We need join method hints which fit specified join order in every join
2539          * level.  For example, Leading(A B C) virtually requires following join
2540          * method hints, if no join method hint supplied:
2541          *   - level 1: none
2542          *   - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2543          *   - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2544          *
2545          * If we already have join method hint which fits specified join order in
2546          * that join level, we leave it as-is and don't add new hints.
2547          */
2548         joinrelids = NULL;
2549         njoinrels = 0;
2550         if (lhint->outer_inner == NULL)
2551         {
2552                 foreach(l, lhint->relations)
2553                 {
2554                         JoinMethodHint *hint;
2555
2556                         relname = (char *)lfirst(l);
2557
2558                         /*
2559                          * Find relid of the relation which has given name.  If we have the
2560                          * name given in Leading hint multiple times in the join, nothing to
2561                          * do.
2562                          */
2563                         relid = find_relid_aliasname(root, relname, initial_rels,
2564                                                                                  hstate->hint_str);
2565
2566                         /* Create bitmap of relids for current join level. */
2567                         joinrelids = bms_add_member(joinrelids, relid);
2568                         njoinrels++;
2569
2570                         /* We never have join method hint for single relation. */
2571                         if (njoinrels < 2)
2572                                 continue;
2573
2574                         /*
2575                          * If we don't have join method hint, create new one for the
2576                          * join combination with all join methods are enabled.
2577                          */
2578                         hint = find_join_hint(joinrelids);
2579                         if (hint == NULL)
2580                         {
2581                                 /*
2582                                  * Here relnames is not set, since Relids bitmap is sufficient
2583                                  * to control paths of this query afterward.
2584                                  */
2585                                 hint = (JoinMethodHint *) JoinMethodHintCreate(
2586                                                                                         lhint->base.hint_str,
2587                                                                                         HINT_LEADING,
2588                                                                                         HINT_KEYWORD_LEADING);
2589                                 hint->base.state = HINT_STATE_USED;
2590                                 hint->nrels = njoinrels;
2591                                 hint->enforce_mask = ENABLE_ALL_JOIN;
2592                                 hint->joinrelids = bms_copy(joinrelids);
2593                         }
2594
2595                         join_method_hints[njoinrels] = hint;
2596
2597                         if (njoinrels >= nbaserel)
2598                                 break;
2599                 }
2600                 bms_free(joinrelids);
2601
2602                 if (njoinrels < 2)
2603                         return;
2604
2605                 /*
2606                  * Delete all join hints which have different combination from Leading
2607                  * hint.
2608                  */
2609                 for (i = 2; i <= njoinrels; i++)
2610                 {
2611                         list_free(hstate->join_hint_level[i]);
2612
2613                         hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2614                 }
2615         }
2616         else
2617         {
2618                 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
2619                                                                                   lhint,
2620                                           root,
2621                                           initial_rels,
2622                                                                                   hstate,
2623                                          &njoinrels,
2624                                                                                   nbaserel);
2625
2626                 /*
2627                  * Delete all join hints which have different combination from Leading
2628                  * hint.
2629                  */
2630                 for (i = 2;i <= nbaserel; i++)
2631                 {
2632                         if (hstate->join_hint_level[i] != NIL)
2633                         {
2634                                 ListCell *prev = NULL;
2635                                 ListCell *next = NULL;
2636                                 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
2637                                 {
2638
2639                                         JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
2640
2641                                         next = lnext(l);
2642
2643                                         if (hint->inner_nrels == 0 &&
2644                                                 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
2645                                                   bms_equal(bms_union(hint->joinrelids, joinrelids),
2646                                                   hint->joinrelids)))
2647                                         {
2648                                                 hstate->join_hint_level[i] =
2649                                                         list_delete_cell(hstate->join_hint_level[i], l,
2650                                                                                          prev);
2651                                         }
2652                                         else
2653                                                 prev = l;
2654                                 }
2655                         }
2656                 }
2657
2658         bms_free(joinrelids);
2659
2660         if (njoinrels < 2)
2661                 return;
2662         }
2663
2664         if (hint_state_enabled(lhint))
2665                 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2666 }
2667
2668 /*
2669  * set_plain_rel_pathlist
2670  *        Build access paths for a plain relation (no subquery, no inheritance)
2671  *
2672  * This function was copied and edited from set_plain_rel_pathlist() in
2673  * src/backend/optimizer/path/allpaths.c
2674  */
2675 static void
2676 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2677 {
2678         /* Consider sequential scan */
2679 #if PG_VERSION_NUM >= 90200
2680         add_path(rel, create_seqscan_path(root, rel, NULL));
2681 #else
2682         add_path(rel, create_seqscan_path(root, rel));
2683 #endif
2684
2685         /* Consider index scans */
2686         create_index_paths(root, rel);
2687
2688         /* Consider TID scans */
2689         create_tidscan_paths(root, rel);
2690
2691         /* Now find the cheapest of the paths for this rel */
2692         set_cheapest(rel);
2693 }
2694
2695 static void
2696 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2697                                   List *initial_rels)
2698 {
2699         ListCell   *l;
2700
2701         foreach(l, initial_rels)
2702         {
2703                 RelOptInfo         *rel = (RelOptInfo *) lfirst(l);
2704                 RangeTblEntry  *rte;
2705                 ScanMethodHint *hint;
2706
2707                 /* Skip relations which we can't choose scan method. */
2708                 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2709                         continue;
2710
2711                 rte = root->simple_rte_array[rel->relid];
2712
2713                 /* We can't force scan method of foreign tables */
2714                 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2715                         continue;
2716
2717                 /*
2718                  * Create scan paths with GUC parameters which are at the beginning of
2719                  * planner if scan method hint is not specified, otherwise use
2720                  * specified hints and mark the hint as used.
2721                  */
2722                 if ((hint = find_scan_hint(root, rel)) == NULL)
2723                         set_scan_config_options(hstate->init_scan_mask,
2724                                                                         hstate->context);
2725                 else
2726                 {
2727                         set_scan_config_options(hint->enforce_mask, hstate->context);
2728                         hint->base.state = HINT_STATE_USED;
2729                 }
2730
2731                 list_free_deep(rel->pathlist);
2732                 rel->pathlist = NIL;
2733                 if (rte->inh)
2734                 {
2735                         /* It's an "append relation", process accordingly */
2736                         set_append_rel_pathlist(root, rel, rel->relid, rte);
2737                 }
2738                 else
2739                 {
2740                         set_plain_rel_pathlist(root, rel, rte);
2741                 }
2742         }
2743
2744         /*
2745          * Restore the GUC variables we set above.
2746          */
2747         set_scan_config_options(hstate->init_scan_mask, hstate->context);
2748 }
2749
2750 /*
2751  * wrapper of make_join_rel()
2752  *
2753  * call make_join_rel() after changing enable_* parameters according to given
2754  * hints.
2755  */
2756 static RelOptInfo *
2757 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2758 {
2759         Relids                  joinrelids;
2760         JoinMethodHint *hint;
2761         RelOptInfo         *rel;
2762         int                             save_nestlevel;
2763
2764         joinrelids = bms_union(rel1->relids, rel2->relids);
2765         hint = find_join_hint(joinrelids);
2766         bms_free(joinrelids);
2767
2768         if (!hint)
2769                 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2770
2771         if (hint->inner_nrels == 0)
2772         {
2773                 save_nestlevel = NewGUCNestLevel();
2774
2775                 set_join_config_options(hint->enforce_mask, current_hint->context);
2776
2777                 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2778                 hint->base.state = HINT_STATE_USED;
2779
2780                 /*
2781                  * Restore the GUC variables we set above.
2782                  */
2783                 AtEOXact_GUC(true, save_nestlevel);
2784         }
2785         else
2786                 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2787
2788         return rel;
2789 }
2790
2791 /*
2792  * TODO : comment
2793  */
2794 static void
2795 add_paths_to_joinrel_wrapper(PlannerInfo *root,
2796                                                          RelOptInfo *joinrel,
2797                                                          RelOptInfo *outerrel,
2798                                                          RelOptInfo *innerrel,
2799                                                          JoinType jointype,
2800                                                          SpecialJoinInfo *sjinfo,
2801                                                          List *restrictlist)
2802 {
2803         ScanMethodHint *scan_hint = NULL;
2804         Relids                  joinrelids;
2805         JoinMethodHint *join_hint;
2806         int                             save_nestlevel;
2807
2808         if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
2809         {
2810                 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
2811                 scan_hint->base.state = HINT_STATE_USED;
2812         }
2813
2814         joinrelids = bms_union(outerrel->relids, innerrel->relids);
2815         join_hint = find_join_hint(joinrelids);
2816         bms_free(joinrelids);
2817
2818         if (join_hint && join_hint->inner_nrels != 0)
2819         {
2820                 save_nestlevel = NewGUCNestLevel();
2821
2822                 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
2823                 {
2824
2825                         set_join_config_options(join_hint->enforce_mask,
2826                                                                         current_hint->context);
2827
2828                         add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2829                                                                  sjinfo, restrictlist);
2830                         join_hint->base.state = HINT_STATE_USED;
2831                 }
2832                 else
2833                 {
2834                         set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2835                         add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2836                                                                  sjinfo, restrictlist);
2837                 }
2838
2839                 /*
2840                  * Restore the GUC variables we set above.
2841                  */
2842                 AtEOXact_GUC(true, save_nestlevel);
2843         }
2844         else
2845                 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
2846                                                          sjinfo, restrictlist);
2847
2848         if (scan_hint != NULL)
2849                 set_scan_config_options(current_hint->init_scan_mask,
2850                                                                 current_hint->context);
2851 }
2852
2853 static int
2854 get_num_baserels(List *initial_rels)
2855 {
2856         int                     nbaserel = 0;
2857         ListCell   *l;
2858
2859         foreach(l, initial_rels)
2860         {
2861                 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2862
2863                 if (rel->reloptkind == RELOPT_BASEREL)
2864                         nbaserel++;
2865                 else if (rel->reloptkind ==RELOPT_JOINREL)
2866                         nbaserel+= bms_num_members(rel->relids);
2867                 else
2868                 {
2869                         /* other values not expected here */
2870                         elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2871                 }
2872         }
2873
2874         return nbaserel;
2875 }
2876
2877 static RelOptInfo *
2878 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2879                                                  List *initial_rels)
2880 {
2881         JoinMethodHint    **join_method_hints;
2882         LeadingHint                *leading_hint = NULL;
2883         int                                     nbaserel;
2884         RelOptInfo                 *rel;
2885         int                                     i;
2886
2887         /*
2888          * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2889          * valid hint is supplied.
2890          */
2891         if (!current_hint)
2892         {
2893                 if (prev_join_search)
2894                         return (*prev_join_search) (root, levels_needed, initial_rels);
2895                 else if (enable_geqo && levels_needed >= geqo_threshold)
2896                         return geqo(root, levels_needed, initial_rels);
2897                 else
2898                         return standard_join_search(root, levels_needed, initial_rels);
2899         }
2900
2901         /* We apply scan method hint rebuild scan path. */
2902         rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2903
2904         /*
2905          * In the case using GEQO, only scan method hints and Set hints have
2906          * effect.  Join method and join order is not controllable by hints.
2907          */
2908         if (enable_geqo && levels_needed >= geqo_threshold)
2909                 return geqo(root, levels_needed, initial_rels);
2910
2911         nbaserel = get_num_baserels(initial_rels);
2912         current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2913         join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2914
2915         transform_join_hints(current_hint, root, nbaserel, initial_rels,
2916                                                  join_method_hints, leading_hint);
2917
2918         rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2919
2920         for (i = 2; i <= nbaserel; i++)
2921         {
2922                 list_free(current_hint->join_hint_level[i]);
2923
2924                 /* free Leading hint only */
2925                 if (join_method_hints[i] != NULL &&
2926                         join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2927                         JoinMethodHintDelete(join_method_hints[i]);
2928         }
2929         pfree(current_hint->join_hint_level);
2930         pfree(join_method_hints);
2931
2932         if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2933                 leading_hint != NULL &&
2934                 hint_state_enabled(leading_hint))
2935                 set_join_config_options(current_hint->init_join_mask,
2936                                                                 current_hint->context);
2937
2938         return rel;
2939 }
2940
2941 /*
2942  * set_rel_pathlist
2943  *        Build access paths for a base relation
2944  *
2945  * This function was copied and edited from set_rel_pathlist() in
2946  * src/backend/optimizer/path/allpaths.c
2947  */
2948 static void
2949 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2950                                  Index rti, RangeTblEntry *rte)
2951 {
2952 #if PG_VERSION_NUM >= 90200
2953         if (IS_DUMMY_REL(rel))
2954         {
2955                 /* We already proved the relation empty, so nothing more to do */
2956         }
2957         else if (rte->inh)
2958 #else
2959         if (rte->inh)
2960 #endif
2961         {
2962                 /* It's an "append relation", process accordingly */
2963                 set_append_rel_pathlist(root, rel, rti, rte);
2964         }
2965         else
2966         {
2967                 if (rel->rtekind == RTE_RELATION)
2968                 {
2969                         if (rte->relkind == RELKIND_RELATION)
2970                         {
2971                                 /* Plain relation */
2972                                 set_plain_rel_pathlist(root, rel, rte);
2973                         }
2974                         else
2975                                 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2976                 }
2977                 else
2978                         elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2979         }
2980 }
2981
2982 #define standard_join_search pg_hint_plan_standard_join_search
2983 #define join_search_one_level pg_hint_plan_join_search_one_level
2984 #define make_join_rel make_join_rel_wrapper
2985 #include "core.c"
2986
2987 #undef make_join_rel
2988 #define make_join_rel pg_hint_plan_make_join_rel
2989 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
2990 #include "make_join_rel.c"