OSDN Git Service

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