OSDN Git Service

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