OSDN Git Service

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