OSDN Git Service

Don't use the term AllHint.
[pghintplan/pg_hint_plan.git] / pg_hint_plan.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_hint_plan.c
4  *                do instructions or hints to the planner using C-style block comments
5  *                of the SQL.
6  *
7  * Copyright (c) 2012, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8  *
9  *-------------------------------------------------------------------------
10  */
11 #include "postgres.h"
12 #include "commands/prepare.h"
13 #include "mb/pg_wchar.h"
14 #include "miscadmin.h"
15 #include "nodes/nodeFuncs.h"
16 #include "optimizer/clauses.h"
17 #include "optimizer/cost.h"
18 #include "optimizer/geqo.h"
19 #include "optimizer/joininfo.h"
20 #include "optimizer/pathnode.h"
21 #include "optimizer/paths.h"
22 #include "optimizer/plancat.h"
23 #include "optimizer/planner.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/restrictinfo.h"
26 #include "parser/scansup.h"
27 #include "tcop/utility.h"
28 #include "utils/lsyscache.h"
29 #include "utils/memutils.h"
30
31 #ifdef PG_MODULE_MAGIC
32 PG_MODULE_MAGIC;
33 #endif
34
35 #if PG_VERSION_NUM < 90100
36 #error unsupported PostgreSQL version
37 #endif
38
39 #define BLOCK_COMMENT_START             "/*"
40 #define BLOCK_COMMENT_END               "*/"
41 #define HINT_COMMENT_KEYWORD    "+"
42 #define HINT_START                              BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
43 #define HINT_END                                BLOCK_COMMENT_END
44
45 /* hint keywords */
46 #define HINT_SEQSCAN                    "SeqScan"
47 #define HINT_INDEXSCAN                  "IndexScan"
48 #define HINT_BITMAPSCAN                 "BitmapScan"
49 #define HINT_TIDSCAN                    "TidScan"
50 #define HINT_NOSEQSCAN                  "NoSeqScan"
51 #define HINT_NOINDEXSCAN                "NoIndexScan"
52 #define HINT_NOBITMAPSCAN               "NoBitmapScan"
53 #define HINT_NOTIDSCAN                  "NoTidScan"
54 #define HINT_NESTLOOP                   "NestLoop"
55 #define HINT_MERGEJOIN                  "MergeJoin"
56 #define HINT_HASHJOIN                   "HashJoin"
57 #define HINT_NONESTLOOP                 "NoNestLoop"
58 #define HINT_NOMERGEJOIN                "NoMergeJoin"
59 #define HINT_NOHASHJOIN                 "NoHashJoin"
60 #define HINT_LEADING                    "Leading"
61 #define HINT_SET                                "Set"
62
63 #define HINT_ARRAY_DEFAULT_INITSIZE 8
64
65 #define parse_ereport(str, detail) \
66         ereport(pg_hint_plan_parse_messages, \
67                         (errmsg("hint syntax error at or near \"%s\"", (str)), \
68                          errdetail detail))
69
70 #define skip_space(str) \
71         while (isspace(*str)) \
72                 str++;
73
74 enum
75 {
76         ENABLE_SEQSCAN = 0x01,
77         ENABLE_INDEXSCAN = 0x02,
78         ENABLE_BITMAPSCAN = 0x04,
79         ENABLE_TIDSCAN = 0x08,
80 } SCAN_TYPE_BITS;
81
82 enum
83 {
84         ENABLE_NESTLOOP = 0x01,
85         ENABLE_MERGEJOIN = 0x02,
86         ENABLE_HASHJOIN = 0x04
87 } JOIN_TYPE_BITS;
88
89 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
90                                                  ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
91 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
92 #define DISABLE_ALL_SCAN 0
93 #define DISABLE_ALL_JOIN 0
94
95 typedef struct Hint Hint;
96 typedef struct HintState HintState;
97
98 typedef Hint *(*HintCreateFunction) (const char *hint_str,
99                                                                          const char *keyword);
100 typedef void (*HintDeleteFunction) (Hint *hint);
101 typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
102 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
103 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
104                                                                                   Query *parse, const char *str);
105
106 /* hint types */
107 #define NUM_HINT_TYPE   4
108 typedef enum HintType
109 {
110         HINT_TYPE_SCAN_METHOD,
111         HINT_TYPE_JOIN_METHOD,
112         HINT_TYPE_LEADING,
113         HINT_TYPE_SET
114 } HintType;
115
116 /* hint status */
117 typedef enum HintStatus
118 {
119         HINT_STATE_NOTUSED = 0,         /* specified relation not used in query */
120         HINT_STATE_USED,                        /* hint is used */
121         HINT_STATE_DUPLICATION,         /* specified hint duplication */
122         HINT_STATE_ERROR                        /* execute error (parse error does not include
123                                                                  * it) */
124 } HintStatus;
125
126 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
127                                                                   (hint)->base.state == HINT_STATE_USED)
128
129 /* common data for all hints. */
130 struct Hint
131 {
132         const char                 *hint_str;           /* must not do pfree */
133         const char                 *keyword;            /* must not do pfree */
134         HintType                        type;
135         HintStatus                      state;
136         HintDeleteFunction      delete_func;
137         HintDumpFunction        dump_func;
138         HintCmpFunction         cmp_func;
139         HintParseFunction       parser_func;
140 };
141
142 /* scan method hints */
143 typedef struct ScanMethodHint
144 {
145         Hint                    base;
146         char               *relname;
147         List               *indexnames;
148         unsigned char   enforce_mask;
149 } ScanMethodHint;
150
151 /* join method hints */
152 typedef struct JoinMethodHint
153 {
154         Hint                    base;
155         int                             nrels;
156         char              **relnames;
157         unsigned char   enforce_mask;
158         Relids                  joinrelids;
159 } JoinMethodHint;
160
161 /* join order hints */
162 typedef struct LeadingHint
163 {
164         Hint    base;
165         List   *relations;              /* relation names specified in Leading hint */
166 } LeadingHint;
167
168 /* change a run-time parameter hints */
169 typedef struct SetHint
170 {
171         Hint    base;
172         char   *name;                           /* name of variable */
173         char   *value;
174 } SetHint;
175
176 /*
177  * Describes a context of hint processing.
178  */
179 struct HintState
180 {
181         char               *hint_str;                   /* original hint string */
182
183         /* all hint */
184         int                             nall_hints;                     /* # of valid all hints */
185         int                             max_all_hints;          /* # of slots for all hints */
186         Hint              **all_hints;                  /* parsed all hints */
187
188         /* # of each hints */
189         int                             num_hints[NUM_HINT_TYPE];
190
191         /* for scan method hints */
192         ScanMethodHint **scan_hints;            /* parsed scan hints */
193         int                             init_scan_mask;         /* initial value scan parameter */
194         Index                   parent_relid;           /* inherit parent table relid */
195         ScanMethodHint *parent_hint;            /* inherit parent table scan hint */
196
197         /* for join method hints */
198         JoinMethodHint **join_hints;            /* parsed join hints */
199         int                             init_join_mask;         /* initial value join parameter */
200         List              **join_hint_level;
201
202         /* for Leading hint */
203         LeadingHint        *leading_hint;               /* parsed last specified Leading hint */
204
205         /* for Set hints */
206         SetHint           **set_hints;                  /* parsed Set hints */
207         GucContext              context;                        /* which GUC parameters can we set? */
208 };
209
210 /*
211  * Describes a hint parser module which is bound with particular hint keyword.
212  */
213 typedef struct HintParser
214 {
215         char                       *keyword;
216         HintCreateFunction      create_func;
217 } HintParser;
218
219 /* Module callbacks */
220 void            _PG_init(void);
221 void            _PG_fini(void);
222
223 static void push_hint(HintState *hstate);
224 static void pop_hint(void);
225
226 static void pg_hint_plan_ProcessUtility(Node *parsetree,
227                                                                                 const char *queryString,
228                                                                                 ParamListInfo params, bool isTopLevel,
229                                                                                 DestReceiver *dest,
230                                                                                 char *completionTag);
231 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
232                                                                                  ParamListInfo boundParams);
233 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
234                                                                                    Oid relationObjectId,
235                                                                                    bool inhparent, RelOptInfo *rel);
236 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
237                                                                                         int levels_needed,
238                                                                                         List *initial_rels);
239
240 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword);
241 static void ScanMethodHintDelete(ScanMethodHint *hint);
242 static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
243 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
244 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
245                                                                            Query *parse, const char *str);
246 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword);
247 static void JoinMethodHintDelete(JoinMethodHint *hint);
248 static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
249 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
250 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
251                                                                            Query *parse, const char *str);
252 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword);
253 static void LeadingHintDelete(LeadingHint *hint);
254 static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
255 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
256 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
257                                                                         Query *parse, const char *str);
258 static Hint *SetHintCreate(const char *hint_str, const char *keyword);
259 static void SetHintDelete(SetHint *hint);
260 static void SetHintDump(SetHint *hint, StringInfo buf);
261 static int SetHintCmp(const SetHint *a, const SetHint *b);
262 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
263                                                                 const char *str);
264
265 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
266                                                                                           int levels_needed,
267                                                                                           List *initial_rels);
268 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
269 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
270                                                                           ListCell *other_rels);
271 static void make_rels_by_clauseless_joins(PlannerInfo *root,
272                                                                                   RelOptInfo *old_rel,
273                                                                                   ListCell *other_rels);
274 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
275 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
276                                                                         Index rti, RangeTblEntry *rte);
277 static List *accumulate_append_subpath(List *subpaths, Path *path);
278 static void set_dummy_rel_pathlist(RelOptInfo *rel);
279 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
280                                                                            RelOptInfo *rel2);
281
282 /* GUC variables */
283 static bool     pg_hint_plan_enable = true;
284 static bool     pg_hint_plan_debug_print = false;
285 static int      pg_hint_plan_parse_messages = INFO;
286
287 static const struct config_enum_entry parse_messages_level_options[] = {
288         {"debug", DEBUG2, true},
289         {"debug5", DEBUG5, false},
290         {"debug4", DEBUG4, false},
291         {"debug3", DEBUG3, false},
292         {"debug2", DEBUG2, false},
293         {"debug1", DEBUG1, false},
294         {"log", LOG, false},
295         {"info", INFO, false},
296         {"notice", NOTICE, false},
297         {"warning", WARNING, false},
298         {"error", ERROR, false},
299         /*
300          * {"fatal", FATAL, true},
301          * {"panic", PANIC, true},
302          */
303         {NULL, 0, false}
304 };
305
306 /* Saved hook values in case of unload */
307 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
308 static planner_hook_type prev_planner = NULL;
309 static get_relation_info_hook_type prev_get_relation_info = NULL;
310 static join_search_hook_type prev_join_search = NULL;
311
312 /* フック関数をまたがって使用する情報を管理する */
313 static HintState *current_hint = NULL;
314
315 /* 有効なヒントをスタック構造で管理する */
316 static List *HintStateStack = NIL;
317
318 /*
319  * EXECUTEコマンド実行時に、ステートメント名を格納する。
320  * その他のコマンドの場合は、NULLに設定する。
321  */
322 static char        *stmt_name = NULL;
323
324 static const HintParser parsers[] = {
325         {HINT_SEQSCAN, ScanMethodHintCreate},
326         {HINT_INDEXSCAN, ScanMethodHintCreate},
327         {HINT_BITMAPSCAN, ScanMethodHintCreate},
328         {HINT_TIDSCAN, ScanMethodHintCreate},
329         {HINT_NOSEQSCAN, ScanMethodHintCreate},
330         {HINT_NOINDEXSCAN, ScanMethodHintCreate},
331         {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
332         {HINT_NOTIDSCAN, ScanMethodHintCreate},
333         {HINT_NESTLOOP, JoinMethodHintCreate},
334         {HINT_MERGEJOIN, JoinMethodHintCreate},
335         {HINT_HASHJOIN, JoinMethodHintCreate},
336         {HINT_NONESTLOOP, JoinMethodHintCreate},
337         {HINT_NOMERGEJOIN, JoinMethodHintCreate},
338         {HINT_NOHASHJOIN, JoinMethodHintCreate},
339         {HINT_LEADING, LeadingHintCreate},
340         {HINT_SET, SetHintCreate},
341         {NULL, NULL}
342 };
343
344 /*
345  * Module load callbacks
346  */
347 void
348 _PG_init(void)
349 {
350         /* Define custom GUC variables. */
351         DefineCustomBoolVariable("pg_hint_plan.enable",
352                          "Force planner to use plans specified in the hint comment preceding to the query.",
353                                                          NULL,
354                                                          &pg_hint_plan_enable,
355                                                          true,
356                                                          PGC_USERSET,
357                                                          0,
358                                                          NULL,
359                                                          NULL,
360                                                          NULL);
361
362         DefineCustomBoolVariable("pg_hint_plan.debug_print",
363                                                          "Logs results of hint parsing.",
364                                                          NULL,
365                                                          &pg_hint_plan_debug_print,
366                                                          false,
367                                                          PGC_USERSET,
368                                                          0,
369                                                          NULL,
370                                                          NULL,
371                                                          NULL);
372
373         DefineCustomEnumVariable("pg_hint_plan.parse_messages",
374                                                          "Messege level of parse errors.",
375                                                          NULL,
376                                                          &pg_hint_plan_parse_messages,
377                                                          INFO,
378                                                          parse_messages_level_options,
379                                                          PGC_USERSET,
380                                                          0,
381                                                          NULL,
382                                                          NULL,
383                                                          NULL);
384
385         /* Install hooks. */
386         prev_ProcessUtility = ProcessUtility_hook;
387         ProcessUtility_hook = pg_hint_plan_ProcessUtility;
388         prev_planner = planner_hook;
389         planner_hook = pg_hint_plan_planner;
390         prev_get_relation_info = get_relation_info_hook;
391         get_relation_info_hook = pg_hint_plan_get_relation_info;
392         prev_join_search = join_search_hook;
393         join_search_hook = pg_hint_plan_join_search;
394 }
395
396 /*
397  * Module unload callback
398  * XXX never called
399  */
400 void
401 _PG_fini(void)
402 {
403         /* Uninstall hooks. */
404         ProcessUtility_hook = prev_ProcessUtility;
405         planner_hook = prev_planner;
406         get_relation_info_hook = prev_get_relation_info;
407         join_search_hook = prev_join_search;
408 }
409
410 /*
411  * create and delete functions the hint object
412  */
413
414 static Hint *
415 ScanMethodHintCreate(const char *hint_str, const char *keyword)
416 {
417         ScanMethodHint *hint;
418
419         hint = palloc(sizeof(ScanMethodHint));
420         hint->base.hint_str = hint_str;
421         hint->base.keyword = keyword;
422         hint->base.type = HINT_TYPE_SCAN_METHOD;
423         hint->base.state = HINT_STATE_NOTUSED;
424         hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
425         hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
426         hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
427         hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
428         hint->relname = NULL;
429         hint->indexnames = NIL;
430         hint->enforce_mask = 0;
431
432         return (Hint *) hint;
433 }
434
435 static void
436 ScanMethodHintDelete(ScanMethodHint *hint)
437 {
438         if (!hint)
439                 return;
440
441         if (hint->relname)
442                 pfree(hint->relname);
443         list_free_deep(hint->indexnames);
444         pfree(hint);
445 }
446
447 static Hint *
448 JoinMethodHintCreate(const char *hint_str, const char *keyword)
449 {
450         JoinMethodHint *hint;
451
452         hint = palloc(sizeof(JoinMethodHint));
453         hint->base.hint_str = hint_str;
454         hint->base.keyword = keyword;
455         hint->base.type = HINT_TYPE_JOIN_METHOD;
456         hint->base.state = HINT_STATE_NOTUSED;
457         hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
458         hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
459         hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
460         hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
461         hint->nrels = 0;
462         hint->relnames = NULL;
463         hint->enforce_mask = 0;
464         hint->joinrelids = NULL;
465
466         return (Hint *) hint;
467 }
468
469 static void
470 JoinMethodHintDelete(JoinMethodHint *hint)
471 {
472         if (!hint)
473                 return;
474
475         if (hint->relnames)
476         {
477                 int     i;
478
479                 for (i = 0; i < hint->nrels; i++)
480                         pfree(hint->relnames[i]);
481                 pfree(hint->relnames);
482         }
483         bms_free(hint->joinrelids);
484         pfree(hint);
485 }
486
487 static Hint *
488 LeadingHintCreate(const char *hint_str, const char *keyword)
489 {
490         LeadingHint        *hint;
491
492         hint = palloc(sizeof(LeadingHint));
493         hint->base.hint_str = hint_str;
494         hint->base.keyword = keyword;
495         hint->base.type = HINT_TYPE_LEADING;
496         hint->base.state = HINT_STATE_NOTUSED;
497         hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
498         hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
499         hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
500         hint->base.parser_func = (HintParseFunction) LeadingHintParse;
501         hint->relations = NIL;
502
503         return (Hint *) hint;
504 }
505
506 static void
507 LeadingHintDelete(LeadingHint *hint)
508 {
509         if (!hint)
510                 return;
511
512         list_free_deep(hint->relations);
513         pfree(hint);
514 }
515
516 static Hint *
517 SetHintCreate(const char *hint_str, const char *keyword)
518 {
519         SetHint    *hint;
520
521         hint = palloc(sizeof(SetHint));
522         hint->base.hint_str = hint_str;
523         hint->base.keyword = keyword;
524         hint->base.type = HINT_TYPE_SET;
525         hint->base.state = HINT_STATE_NOTUSED;
526         hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
527         hint->base.dump_func = (HintDumpFunction) SetHintDump;
528         hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
529         hint->base.parser_func = (HintParseFunction) SetHintParse;
530         hint->name = NULL;
531         hint->value = NULL;
532
533         return (Hint *) hint;
534 }
535
536 static void
537 SetHintDelete(SetHint *hint)
538 {
539         if (!hint)
540                 return;
541
542         if (hint->name)
543                 pfree(hint->name);
544         if (hint->value)
545                 pfree(hint->value);
546         pfree(hint);
547 }
548
549 static HintState *
550 HintStateCreate(void)
551 {
552         HintState   *hstate;
553
554         hstate = palloc(sizeof(HintState));
555         hstate->hint_str = NULL;
556         hstate->nall_hints = 0;
557         hstate->max_all_hints = 0;
558         hstate->all_hints = NULL;
559         memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
560         hstate->scan_hints = NULL;
561         hstate->init_scan_mask = 0;
562         hstate->parent_relid = 0;
563         hstate->parent_hint = NULL;
564         hstate->join_hints = NULL;
565         hstate->init_join_mask = 0;
566         hstate->join_hint_level = NULL;
567         hstate->leading_hint = NULL;
568         hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
569         hstate->set_hints = NULL;
570
571         return hstate;
572 }
573
574 static void
575 HintStateDelete(HintState *hstate)
576 {
577         int                     i;
578
579         if (!hstate)
580                 return;
581
582         if (hstate->hint_str)
583                 pfree(hstate->hint_str);
584
585         for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
586                 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
587         if (hstate->all_hints)
588                 pfree(hstate->all_hints);
589 }
590
591 /*
592  * dump functions
593  */
594
595 static void
596 dump_quote_value(StringInfo buf, const char *value)
597 {
598         bool            need_quote = false;
599         const char *str;
600
601         for (str = value; *str != '\0'; str++)
602         {
603                 if (isspace(*str) || *str == ')' || *str == '"')
604                 {
605                         need_quote = true;
606                         appendStringInfoCharMacro(buf, '"');
607                         break;
608                 }
609         }
610
611         for (str = value; *str != '\0'; str++)
612         {
613                 if (*str == '"')
614                         appendStringInfoCharMacro(buf, '"');
615
616                 appendStringInfoCharMacro(buf, *str);
617         }
618
619         if (need_quote)
620                 appendStringInfoCharMacro(buf, '"');
621 }
622
623 static void
624 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
625 {
626         ListCell   *l;
627
628         appendStringInfo(buf, "%s(", hint->base.keyword);
629         dump_quote_value(buf, hint->relname);
630         foreach(l, hint->indexnames)
631         {
632                 appendStringInfoCharMacro(buf, ' ');
633                 dump_quote_value(buf, (char *) lfirst(l));
634         }
635         appendStringInfoString(buf, ")\n");
636 }
637
638 static void
639 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
640 {
641         int     i;
642
643         appendStringInfo(buf, "%s(", hint->base.keyword);
644         dump_quote_value(buf, hint->relnames[0]);
645         for (i = 1; i < hint->nrels; i++)
646         {
647                 appendStringInfoCharMacro(buf, ' ');
648                 dump_quote_value(buf, hint->relnames[i]);
649         }
650         appendStringInfoString(buf, ")\n");
651
652 }
653
654 static void
655 LeadingHintDump(LeadingHint *hint, StringInfo buf)
656 {
657         bool            is_first;
658         ListCell   *l;
659
660         appendStringInfo(buf, "%s(", HINT_LEADING);
661         is_first = true;
662         foreach(l, hint->relations)
663         {
664                 if (is_first)
665                         is_first = false;
666                 else
667                         appendStringInfoCharMacro(buf, ' ');
668
669                 dump_quote_value(buf, (char *) lfirst(l));
670         }
671
672         appendStringInfoString(buf, ")\n");
673 }
674
675 static void
676 SetHintDump(SetHint *hint, StringInfo buf)
677 {
678         appendStringInfo(buf, "%s(", HINT_SET);
679         dump_quote_value(buf, hint->name);
680         appendStringInfoCharMacro(buf, ' ');
681         dump_quote_value(buf, hint->value);
682         appendStringInfo(buf, ")\n");
683 }
684
685 static void
686 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
687                           HintStatus state)
688 {
689         int     i;
690
691         appendStringInfo(buf, "%s:\n", title);
692         for (i = 0; i < hstate->nall_hints; i++)
693         {
694                 if (hstate->all_hints[i]->state != state)
695                         continue;
696
697                 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
698         }
699 }
700
701 static void
702 HintStateDump(HintState *hstate)
703 {
704         StringInfoData  buf;
705
706         if (!hstate)
707         {
708                 elog(LOG, "pg_hint_plan:\nno hint");
709                 return;
710         }
711
712         initStringInfo(&buf);
713
714         appendStringInfoString(&buf, "pg_hint_plan:\n");
715         all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
716         all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
717         all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
718         all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
719
720         elog(LOG, "%s", buf.data);
721
722         pfree(buf.data);
723 }
724
725 /*
726  * compare functions
727  */
728
729 static int
730 RelnameCmp(const void *a, const void *b)
731 {
732         const char *relnamea = *((const char **) a);
733         const char *relnameb = *((const char **) b);
734
735         return strcmp(relnamea, relnameb);
736 }
737
738 static int
739 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
740 {
741         return RelnameCmp(&a->relname, &b->relname);
742 }
743
744 static int
745 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
746 {
747         int     i;
748
749         if (a->nrels != b->nrels)
750                 return a->nrels - b->nrels;
751
752         for (i = 0; i < a->nrels; i++)
753         {
754                 int     result;
755                 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
756                         return result;
757         }
758
759         return 0;
760 }
761
762 static int
763 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
764 {
765         return 0;
766 }
767
768 static int
769 SetHintCmp(const SetHint *a, const SetHint *b)
770 {
771         return strcmp(a->name, b->name);
772 }
773
774 static int
775 HintCmp(const void *a, const void *b)
776 {
777         const Hint *hinta = *((const Hint **) a);
778         const Hint *hintb = *((const Hint **) b);
779
780         if (hinta->type != hintb->type)
781                 return hinta->type - hintb->type;
782
783         return hinta->cmp_func(hinta, hintb);
784
785 }
786
787 /* ヒント句で指定した順を返す */
788 static int
789 HintCmpIsOrder(const void *a, const void *b)
790 {
791         const Hint *hinta = *((const Hint **) a);
792         const Hint *hintb = *((const Hint **) b);
793         int             result;
794
795         result = HintCmp(a, b);
796         if (result == 0)
797                 result = hinta->hint_str - hintb->hint_str;
798
799         return result;
800 }
801
802 /*
803  * parse functions
804  */
805
806 static const char *
807 parse_keyword(const char *str, StringInfo buf)
808 {
809         skip_space(str);
810
811         while (!isspace(*str) && *str != '(' && *str != '\0')
812                 appendStringInfoCharMacro(buf, *str++);
813
814         return str;
815 }
816
817 static const char *
818 skip_opened_parenthesis(const char *str)
819 {
820         skip_space(str);
821
822         if (*str != '(')
823         {
824                 parse_ereport(str, ("Opening parenthesis is necessary."));
825                 return NULL;
826         }
827
828         str++;
829
830         return str;
831 }
832
833 static const char *
834 skip_closed_parenthesis(const char *str)
835 {
836         skip_space(str);
837
838         if (*str != ')')
839         {
840                 parse_ereport(str, ("Closing parenthesis is necessary."));
841                 return NULL;
842         }
843
844         str++;
845
846         return str;
847 }
848
849 /*
850  * 二重引用符で囲まれているかもしれないトークンを読み取り word 引数に palloc
851  * で確保したバッファに格納してそのポインタを返す。
852  *
853  * 正常にパースできた場合は残りの文字列の先頭位置を、異常があった場合は NULL を
854  * 返す。
855  * truncateがtrueの場合は、NAMEDATALENに切り詰める。
856  */
857 static const char *
858 parse_quote_value(const char *str, char **word, char *value_type, bool truncate)
859 {
860         StringInfoData  buf;
861         bool                    in_quote;
862
863         /* 先頭のスペースは読み飛ばす。 */
864         skip_space(str);
865
866         initStringInfo(&buf);
867         if (*str == '"')
868         {
869                 str++;
870                 in_quote = true;
871         }
872         else
873                 in_quote = false;
874
875         while (true)
876         {
877                 if (in_quote)
878                 {
879                         /* 二重引用符が閉じられていない場合はパース中断 */
880                         if (*str == '\0')
881                         {
882                                 pfree(buf.data);
883                                 parse_ereport(str, ("Unterminated quoted %s.", value_type));
884                                 return NULL;
885                         }
886
887                         /*
888                          * エスケープ対象のダブルクウォートをスキップする。
889                          * もしブロックコメントの開始文字列や終了文字列もオブジェクト名とし
890                          * て使用したい場合は、/ と * もエスケープ対象とすることで使用できる
891                          * が、処理対象としていない。もしテーブル名にこれらの文字が含まれる
892                          * 場合は、エイリアスを指定する必要がある。
893                          */
894                         if (*str == '"')
895                         {
896                                 str++;
897                                 if (*str != '"')
898                                         break;
899                         }
900                 }
901                 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
902                         break;
903
904                 appendStringInfoCharMacro(&buf, *str++);
905         }
906
907         if (buf.len == 0)
908         {
909                 char   *type;
910
911                 type = pstrdup(value_type);
912                 type[0] = toupper(type[0]);
913                 parse_ereport(str, ("%s is necessary.", type));
914
915                 pfree(buf.data);
916                 pfree(type);
917
918                 return NULL;
919         }
920
921         /* Truncate name if it's overlength */
922         if (truncate)
923                 truncate_identifier(buf.data, strlen(buf.data), true);
924
925         *word = buf.data;
926
927         return str;
928 }
929
930 static void
931 parse_hints(HintState *hstate, Query *parse, const char *str)
932 {
933         StringInfoData  buf;
934         char               *head;
935
936         initStringInfo(&buf);
937         while (*str != '\0')
938         {
939                 const HintParser *parser;
940
941                 /* in error message, we output the comment including the keyword. */
942                 head = (char *) str;
943
944                 /* parse only the keyword of the hint. */
945                 resetStringInfo(&buf);
946                 str = parse_keyword(str, &buf);
947
948                 for (parser = parsers; parser->keyword != NULL; parser++)
949                 {
950                         char   *keyword = parser->keyword;
951                         Hint   *hint;
952
953                         if (strcasecmp(buf.data, keyword) != 0)
954                                 continue;
955
956                         hint = parser->create_func(head, keyword);
957
958                         /* parser of each hint does parse in a parenthesis. */
959                         if ((str = skip_opened_parenthesis(str)) == NULL ||
960                                 (str = hint->parser_func(hint, hstate, parse, str)) == NULL ||
961                                 (str = skip_closed_parenthesis(str)) == NULL)
962                         {
963                                 hint->delete_func(hint);
964                                 pfree(buf.data);
965                                 return;
966                         }
967
968                         /*
969                          * 出来上がったヒント情報を追加。スロットが足りない場合は二倍に拡張
970                          * する。
971                          */
972                         if (hstate->nall_hints == 0)
973                         {
974                                 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
975                                 hstate->all_hints = (Hint **)
976                                         palloc(sizeof(Hint *) * hstate->max_all_hints);
977                         }
978                         else if (hstate->nall_hints == hstate->max_all_hints)
979                         {
980                                 hstate->max_all_hints *= 2;
981                                 hstate->all_hints = (Hint **)
982                                         repalloc(hstate->all_hints,
983                                                          sizeof(Hint *) * hstate->max_all_hints);
984                         }
985
986                         hstate->all_hints[hstate->nall_hints] = hint;
987                         hstate->nall_hints++;
988
989                         skip_space(str);
990
991                         break;
992                 }
993
994                 if (parser->keyword == NULL)
995                 {
996                         parse_ereport(head,
997                                                   ("Unrecognized hint keyword \"%s\".", buf.data));
998                         pfree(buf.data);
999                         return;
1000                 }
1001         }
1002
1003         pfree(buf.data);
1004 }
1005
1006 /*
1007  * Do basic parsing of the query head comment.
1008  */
1009 static HintState *
1010 parse_head_comment(Query *parse)
1011 {
1012         const char *p;
1013         char       *head;
1014         char       *tail;
1015         int                     len;
1016         int                     i;
1017         HintState   *hstate;
1018
1019         /* get client-supplied query string. */
1020         if (stmt_name)
1021         {
1022                 PreparedStatement  *entry;
1023
1024                 entry = FetchPreparedStatement(stmt_name, true);
1025                 p = entry->plansource->query_string;
1026         }
1027         else
1028                 p = debug_query_string;
1029
1030         if (p == NULL)
1031                 return NULL;
1032
1033         /* extract query head comment. */
1034         len = strlen(HINT_START);
1035         skip_space(p);
1036         if (strncmp(p, HINT_START, len))
1037                 return NULL;
1038
1039         head = (char *) p;
1040         p += len;
1041         skip_space(p);
1042
1043         /* find hint end keyword. */
1044         if ((tail = strstr(p, HINT_END)) == NULL)
1045         {
1046                 parse_ereport(head, ("Unterminated block comment."));
1047                 return NULL;
1048         }
1049
1050         /* 入れ子にしたブロックコメントはサポートしない */
1051         if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1052         {
1053                 parse_ereport(head, ("Nested block comments are not supported."));
1054                 return NULL;
1055         }
1056
1057         /* ヒント句部分を切り出す */
1058         len = tail - p;
1059         head = palloc(len + 1);
1060         memcpy(head, p, len);
1061         head[len] = '\0';
1062         p = head;
1063
1064         hstate = HintStateCreate();
1065         hstate->hint_str = head;
1066
1067         /* parse each hint. */
1068         parse_hints(hstate, parse, p);
1069
1070         /* When nothing specified a hint, we free HintState and returns NULL. */
1071         if (hstate->nall_hints == 0)
1072         {
1073                 HintStateDelete(hstate);
1074                 return NULL;
1075         }
1076
1077         /* パースしたヒントを並び替える */
1078         qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1079                   HintCmpIsOrder);
1080
1081         /* 重複したヒントを検索する */
1082         for (i = 0; i < hstate->nall_hints; i++)
1083         {
1084                 Hint   *hint = hstate->all_hints[i];
1085
1086                 hstate->num_hints[hint->type]++;
1087
1088                 if (i + 1 >= hstate->nall_hints)
1089                         break;
1090
1091                 if (HintCmp(hstate->all_hints + i, hstate->all_hints + i + 1) == 0)
1092                 {
1093                         const char *HintTypeName[] = {
1094                                 "scan method", "join method", "leading", "set"
1095                         };
1096
1097                         parse_ereport(hstate->all_hints[i]->hint_str,
1098                                                   ("Conflict %s hint.", HintTypeName[hint->type]));
1099                         hstate->all_hints[i]->state = HINT_STATE_DUPLICATION;
1100                 }
1101         }
1102
1103         hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1104         hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1105                 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1106         hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1107                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1108                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1109                 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1110         hstate->set_hints = (SetHint **) hstate->all_hints +
1111                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1112                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1113                 hstate->num_hints[HINT_TYPE_LEADING];
1114
1115         return hstate;
1116 }
1117
1118 /*
1119  * スキャン方式ヒントのカッコ内をパースする
1120  */
1121 static const char *
1122 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1123                                         const char *str)
1124 {
1125         const char *keyword = hint->base.keyword;
1126
1127         /*
1128          * スキャン方式のヒントでリレーション名が読み取れない場合はヒント無効
1129          */
1130         if ((str = parse_quote_value(str, &hint->relname, "relation name", true))
1131                 == NULL)
1132                 return NULL;
1133
1134         skip_space(str);
1135
1136         /*
1137          * インデックスリストを受け付けるヒントであれば、インデックス参照をパース
1138          * する。
1139          */
1140         if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
1141                 strcmp(keyword, HINT_BITMAPSCAN) == 0)
1142         {
1143                 while (*str != ')' && *str != '\0')
1144                 {
1145                         char       *indexname;
1146
1147                         str = parse_quote_value(str, &indexname, "index name", true);
1148                         if (str == NULL)
1149                                 return NULL;
1150
1151                         hint->indexnames = lappend(hint->indexnames, indexname);
1152                         skip_space(str);
1153                 }
1154         }
1155
1156         /*
1157          * ヒントごとに決まっている許容スキャン方式をビットマスクとして設定
1158          */
1159         if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1160                 hint->enforce_mask = ENABLE_SEQSCAN;
1161         else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1162                 hint->enforce_mask = ENABLE_INDEXSCAN;
1163         else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1164                 hint->enforce_mask = ENABLE_BITMAPSCAN;
1165         else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1166                 hint->enforce_mask = ENABLE_TIDSCAN;
1167         else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1168                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1169         else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1170                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1171         else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1172                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1173         else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1174                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1175         else
1176         {
1177                 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1178                 return NULL;
1179         }
1180
1181         return str;
1182 }
1183
1184 static const char *
1185 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1186                                         const char *str)
1187 {
1188         char       *relname;
1189         const char *keyword = hint->base.keyword;
1190
1191         skip_space(str);
1192
1193         hint->relnames = palloc(sizeof(char *));
1194
1195         while ((str = parse_quote_value(str, &relname, "relation name", true))
1196                    != NULL)
1197         {
1198                 hint->nrels++;
1199                 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1200                 hint->relnames[hint->nrels - 1] = relname;
1201
1202                 skip_space(str);
1203                 if (*str == ')')
1204                         break;
1205         }
1206
1207         if (str == NULL)
1208                 return NULL;
1209
1210         /* Join 対象のテーブルは最低でも2つ指定する必要がある */
1211         if (hint->nrels < 2)
1212         {
1213                 parse_ereport(str,
1214                                           ("%s hint requires at least two relations.",
1215                                            hint->base.keyword));
1216                 hint->base.state = HINT_STATE_ERROR;
1217         }
1218
1219         /* テーブル名順にソートする */
1220         qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1221
1222         if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1223                 hint->enforce_mask = ENABLE_NESTLOOP;
1224         else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1225                 hint->enforce_mask = ENABLE_MERGEJOIN;
1226         else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1227                 hint->enforce_mask = ENABLE_HASHJOIN;
1228         else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1229                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1230         else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1231                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1232         else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1233                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1234         else
1235         {
1236                 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1237                 return NULL;
1238         }
1239
1240         return str;
1241 }
1242
1243 static const char *
1244 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1245                                  const char *str)
1246 {
1247         skip_space(str);
1248
1249         while (*str != ')')
1250         {
1251                 char   *relname;
1252
1253                 if ((str = parse_quote_value(str, &relname, "relation name", true))
1254                         == NULL)
1255                         return NULL;
1256
1257                 hint->relations = lappend(hint->relations, relname);
1258
1259                 skip_space(str);
1260         }
1261
1262         /* テーブル指定が2つ未満の場合は、Leading ヒントはエラーとする */
1263         if (list_length(hint->relations) < 2)
1264         {
1265                 parse_ereport(hint->base.hint_str,
1266                                           ("%s hint requires at least two relations.",
1267                                            HINT_LEADING));
1268                 hint->base.state = HINT_STATE_ERROR;
1269         }
1270
1271         return str;
1272 }
1273
1274 static const char *
1275 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1276 {
1277         if ((str = parse_quote_value(str, &hint->name, "parameter name", true))
1278                 == NULL ||
1279                 (str = parse_quote_value(str, &hint->value, "parameter value", false))
1280                 == NULL)
1281                 return NULL;
1282
1283         return str;
1284 }
1285
1286 /*
1287  * set GUC parameter functions
1288  */
1289
1290 static int
1291 set_config_option_wrapper(const char *name, const char *value,
1292                                                   GucContext context, GucSource source,
1293                                                   GucAction action, bool changeVal, int elevel)
1294 {
1295         int                             result = 0;
1296         MemoryContext   ccxt = CurrentMemoryContext;
1297
1298         PG_TRY();
1299         {
1300                 result = set_config_option(name, value, context, source,
1301                                                                    action, changeVal);
1302         }
1303         PG_CATCH();
1304         {
1305                 ErrorData          *errdata;
1306
1307                 /* Save error info */
1308                 MemoryContextSwitchTo(ccxt);
1309                 errdata = CopyErrorData();
1310                 FlushErrorState();
1311
1312                 ereport(elevel, (errcode(errdata->sqlerrcode),
1313                                 errmsg("%s", errdata->message),
1314                                 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1315                                 errdata->hint ? errhint("%s", errdata->hint) : 0));
1316                 FreeErrorData(errdata);
1317         }
1318         PG_END_TRY();
1319
1320         return result;
1321 }
1322
1323 static int
1324 set_config_options(SetHint **options, int noptions, GucContext context)
1325 {
1326         int     i;
1327         int     save_nestlevel;
1328
1329         save_nestlevel = NewGUCNestLevel();
1330
1331         for (i = 0; i < noptions; i++)
1332         {
1333                 SetHint    *hint = options[i];
1334                 int                     result;
1335
1336                 if (!hint_state_enabled(hint))
1337                         continue;
1338
1339                 result = set_config_option_wrapper(hint->name, hint->value, context,
1340                                                                                    PGC_S_SESSION, GUC_ACTION_SAVE, true,
1341                                                                                    pg_hint_plan_parse_messages);
1342                 if (result != 0)
1343                         hint->base.state = HINT_STATE_USED;
1344                 else
1345                         hint->base.state = HINT_STATE_ERROR;
1346         }
1347
1348         return save_nestlevel;
1349 }
1350
1351 #define SET_CONFIG_OPTION(name, type_bits) \
1352         set_config_option_wrapper((name), \
1353                 (mask & (type_bits)) ? "true" : "false", \
1354                 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1355
1356 static void
1357 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1358 {
1359         unsigned char   mask;
1360
1361         if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1362                 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1363                 )
1364                 mask = enforce_mask;
1365         else
1366                 mask = enforce_mask & current_hint->init_scan_mask;
1367
1368         SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1369         SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1370         SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1371         SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1372 }
1373
1374 static void
1375 set_join_config_options(unsigned char enforce_mask, GucContext context)
1376 {
1377         unsigned char   mask;
1378
1379         if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1380                 enforce_mask == ENABLE_HASHJOIN)
1381                 mask = enforce_mask;
1382         else
1383                 mask = enforce_mask & current_hint->init_join_mask;
1384
1385         SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1386         SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1387         SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1388 }
1389
1390 /*
1391  * pg_hint_plan hook functions
1392  */
1393
1394 static void
1395 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1396                                                         ParamListInfo params, bool isTopLevel,
1397                                                         DestReceiver *dest, char *completionTag)
1398 {
1399         Node                               *node;
1400
1401         if (!pg_hint_plan_enable)
1402         {
1403                 if (prev_ProcessUtility)
1404                         (*prev_ProcessUtility) (parsetree, queryString, params,
1405                                                                         isTopLevel, dest, completionTag);
1406                 else
1407                         standard_ProcessUtility(parsetree, queryString, params,
1408                                                                         isTopLevel, dest, completionTag);
1409
1410                 return;
1411         }
1412
1413         node = parsetree;
1414         if (IsA(node, ExplainStmt))
1415         {
1416                 /*
1417                  * EXPLAIN対象のクエリのパースツリーを取得する
1418                  */
1419                 ExplainStmt        *stmt;
1420                 Query              *query;
1421
1422                 stmt = (ExplainStmt *) node;
1423
1424                 Assert(IsA(stmt->query, Query));
1425                 query = (Query *) stmt->query;
1426
1427                 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1428                         node = query->utilityStmt;
1429         }
1430
1431         /*
1432          * EXECUTEコマンドならば、PREPARE時に指定されたクエリ文字列を取得し、ヒント
1433          * 句の候補として設定する
1434          */
1435         if (IsA(node, ExecuteStmt))
1436         {
1437                 ExecuteStmt        *stmt;
1438
1439                 stmt = (ExecuteStmt *) node;
1440                 stmt_name = stmt->name;
1441         }
1442
1443         if (stmt_name)
1444         {
1445                 PG_TRY();
1446                 {
1447                         if (prev_ProcessUtility)
1448                                 (*prev_ProcessUtility) (parsetree, queryString, params,
1449                                                                                 isTopLevel, dest, completionTag);
1450                         else
1451                                 standard_ProcessUtility(parsetree, queryString, params,
1452                                                                                 isTopLevel, dest, completionTag);
1453                 }
1454                 PG_CATCH();
1455                 {
1456                         stmt_name = NULL;
1457                         PG_RE_THROW();
1458                 }
1459                 PG_END_TRY();
1460
1461                 stmt_name = NULL;
1462
1463                 return;
1464         }
1465
1466         if (prev_ProcessUtility)
1467                 (*prev_ProcessUtility) (parsetree, queryString, params,
1468                                                                 isTopLevel, dest, completionTag);
1469         else
1470                 standard_ProcessUtility(parsetree, queryString, params,
1471                                                                 isTopLevel, dest, completionTag);
1472 }
1473
1474 /*
1475  * ヒント用スタック構造にヒントをプッシュする。なお、List構造体でヒント用スタッ
1476  * ク構造を実装していて、リストの先頭がスタックの一番上に該当する。
1477  */
1478 static void
1479 push_hint(HintState *hstate)
1480 {
1481         /* 新しいヒントをスタックに積む。 */
1482         HintStateStack = lcons(hstate, HintStateStack);
1483
1484         /*
1485          * 先ほどスタックに積んだヒントを現在のヒントとしてcurrent_hintに格納する。
1486          */
1487         current_hint = hstate;
1488 }
1489
1490 /*
1491  * ヒント用スタック構造から不要になったヒントをポップする。取り出されたヒントは
1492  * 自動的に破棄される。
1493  */
1494 static void
1495 pop_hint(void)
1496 {
1497         /* ヒントのスタックが空の場合はエラーを返す */
1498         if(HintStateStack == NIL)
1499                 elog(ERROR, "hint stack is empty");
1500
1501         /*
1502          * ヒントのスタックから一番上のものを取り出して解放する。 current_hintは
1503          * 常に最上段ヒントを指す(スタックが空の場合はNULL)。
1504          */
1505         HintStateStack = list_delete_first(HintStateStack);
1506         HintStateDelete(current_hint);
1507         if(HintStateStack == NIL)
1508                 current_hint = NULL;
1509         else
1510                 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1511 }
1512
1513 static PlannedStmt *
1514 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1515 {
1516         int                             save_nestlevel;
1517         PlannedStmt        *result;
1518         HintState          *hstate;
1519
1520         /*
1521          * pg_hint_planが無効である場合は通常のparser処理をおこなう。
1522          * 他のフック関数で実行されるhint処理をスキップするために、current_hint 変数
1523          * をNULLに設定しておく。
1524          */
1525         if (!pg_hint_plan_enable)
1526         {
1527                 current_hint = NULL;
1528
1529                 if (prev_planner)
1530                         return (*prev_planner) (parse, cursorOptions, boundParams);
1531                 else
1532                         return standard_planner(parse, cursorOptions, boundParams);
1533         }
1534
1535         /* 有効なヒント句を保存する。 */
1536         hstate = parse_head_comment(parse);
1537
1538         /*
1539          * hintが指定されない、または空のhintを指定された場合は通常のparser処理をお
1540          * こなう。
1541          * 他のフック関数で実行されるhint処理をスキップするために、current_hint 変数
1542          * をNULLに設定しておく。
1543          */
1544         if (!hstate)
1545         {
1546                 current_hint = NULL;
1547
1548                 if (prev_planner)
1549                         return (*prev_planner) (parse, cursorOptions, boundParams);
1550                 else
1551                         return standard_planner(parse, cursorOptions, boundParams);
1552         }
1553
1554         /* 現在のヒントをスタックに積む。 */
1555         push_hint(hstate);
1556
1557         /* Set hint で指定されたGUCパラメータを設定する */
1558         save_nestlevel = set_config_options(current_hint->set_hints,
1559                                                                                 current_hint->num_hints[HINT_TYPE_SET],
1560                                                                                 current_hint->context);
1561
1562         if (enable_seqscan)
1563                 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1564         if (enable_indexscan)
1565                 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1566         if (enable_bitmapscan)
1567                 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1568         if (enable_tidscan)
1569                 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1570         if (enable_nestloop)
1571                 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1572         if (enable_mergejoin)
1573                 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1574         if (enable_hashjoin)
1575                 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1576
1577         /*
1578          * プラン作成中にエラーとなった場合、GUCパラメータと current_hintを
1579          * pg_hint_plan_planner 関数の実行前の状態に戻す。
1580          */
1581         PG_TRY();
1582         {
1583                 if (prev_planner)
1584                         result = (*prev_planner) (parse, cursorOptions, boundParams);
1585                 else
1586                         result = standard_planner(parse, cursorOptions, boundParams);
1587         }
1588         PG_CATCH();
1589         {
1590                 /*
1591                  * プランナ起動前の状態に戻すため、GUCパラメータを復元し、ヒント情報を
1592                  * 一つ削除する。
1593                  */
1594                 AtEOXact_GUC(true, save_nestlevel);
1595                 pop_hint();
1596                 PG_RE_THROW();
1597         }
1598         PG_END_TRY();
1599
1600         /*
1601          * Print hint if debugging.
1602          */
1603         if (pg_hint_plan_debug_print)
1604                 HintStateDump(current_hint);
1605
1606         /*
1607          * プランナ起動前の状態に戻すため、GUCパラメータを復元し、ヒント情報を一つ
1608          * 削除する。
1609          */
1610         AtEOXact_GUC(true, save_nestlevel);
1611         pop_hint();
1612
1613         return result;
1614 }
1615
1616 /*
1617  * aliasnameと一致するSCANヒントを探す
1618  */
1619 static ScanMethodHint *
1620 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1621 {
1622         RangeTblEntry  *rte;
1623         int                             i;
1624
1625         /*
1626          * RELOPT_BASEREL でなければ、scan method ヒントが適用しない。
1627          * 子テーブルの場合はRELOPT_OTHER_MEMBER_RELとなるが、サポート対象外とする。
1628          * また、通常のリレーション以外は、スキャン方式を選択できない。
1629          */
1630         if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1631                 return NULL;
1632
1633         rte = root->simple_rte_array[rel->relid];
1634
1635         /* 外部表はスキャン方式が選択できない。 */
1636         if (rte->relkind == RELKIND_FOREIGN_TABLE)
1637                 return NULL;
1638
1639         /*
1640          * スキャン方式のヒントのリストから、検索対象のリレーションと名称が一致する
1641          * ヒントを検索する。
1642          */
1643         for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1644         {
1645                 ScanMethodHint *hint = current_hint->scan_hints[i];
1646
1647                 /* すでに無効となっているヒントは検索対象にしない。 */
1648                 if (!hint_state_enabled(hint))
1649                         continue;
1650
1651                 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1652                         return hint;
1653         }
1654
1655         return NULL;
1656 }
1657
1658 static void
1659 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1660 {
1661         ListCell           *cell;
1662         ListCell           *prev;
1663         ListCell           *next;
1664
1665         /*
1666          * We delete all the IndexOptInfo list and prevent you from being usable by
1667          * a scan.
1668          */
1669         if (hint->enforce_mask == ENABLE_SEQSCAN ||
1670                 hint->enforce_mask == ENABLE_TIDSCAN)
1671         {
1672                 list_free_deep(rel->indexlist);
1673                 rel->indexlist = NIL;
1674                 hint->base.state = HINT_STATE_USED;
1675
1676                 return;
1677         }
1678
1679         /*
1680          * When a list of indexes is not specified, we just use all indexes.
1681          */
1682         if (hint->indexnames == NIL)
1683                 return;
1684
1685         /*
1686          * Leaving only an specified index, we delete it from a IndexOptInfo list
1687          * other than it.
1688          */
1689         prev = NULL;
1690         for (cell = list_head(rel->indexlist); cell; cell = next)
1691         {
1692                 IndexOptInfo   *info = (IndexOptInfo *) lfirst(cell);
1693                 char               *indexname = get_rel_name(info->indexoid);
1694                 ListCell           *l;
1695                 bool                    use_index = false;
1696
1697                 next = lnext(cell);
1698
1699                 foreach(l, hint->indexnames)
1700                 {
1701                         if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1702                         {
1703                                 use_index = true;
1704                                 break;
1705                         }
1706                 }
1707
1708                 if (!use_index)
1709                         rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1710                 else
1711                         prev = cell;
1712
1713                 pfree(indexname);
1714         }
1715 }
1716
1717 static void
1718 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1719                                                            bool inhparent, RelOptInfo *rel)
1720 {
1721         ScanMethodHint *hint;
1722
1723         if (prev_get_relation_info)
1724                 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1725
1726         /* 有効なヒントが指定されなかった場合は処理をスキップする。 */
1727         if (!current_hint)
1728                 return;
1729
1730         if (inhparent)
1731         {
1732                 /* store does relids of parent table. */
1733                 current_hint->parent_relid = rel->relid;
1734         }
1735         else if (current_hint->parent_relid != 0)
1736         {
1737                 /*
1738                  * We use the same GUC parameter if this table is the child table of a
1739                  * table called pg_hint_plan_get_relation_info just before that.
1740                  */
1741                 ListCell   *l;
1742
1743                 /* append_rel_list contains all append rels; ignore others */
1744                 foreach(l, root->append_rel_list)
1745                 {
1746                         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1747
1748                         /* This rel is child table. */
1749                         if (appinfo->parent_relid == current_hint->parent_relid &&
1750                                 appinfo->child_relid == rel->relid)
1751                         {
1752                                 if (current_hint->parent_hint)
1753                                         delete_indexes(current_hint->parent_hint, rel);
1754
1755                                 return;
1756                         }
1757                 }
1758
1759                 /* This rel is not inherit table. */
1760                 current_hint->parent_relid = 0;
1761                 current_hint->parent_hint = NULL;
1762         }
1763
1764         /* scan hint が指定されない場合は、GUCパラメータをリセットする。 */
1765         if ((hint = find_scan_hint(root, rel)) == NULL)
1766         {
1767                 set_scan_config_options(current_hint->init_scan_mask,
1768                                                                 current_hint->context);
1769                 return;
1770         }
1771         set_scan_config_options(hint->enforce_mask, current_hint->context);
1772         hint->base.state = HINT_STATE_USED;
1773         if (inhparent)
1774                 current_hint->parent_hint = hint;
1775
1776         delete_indexes(hint, rel);
1777 }
1778
1779 /*
1780  * aliasnameがクエリ中に指定した別名と一致する場合は、そのインデックスを返し、一
1781  * 致する別名がなければ0を返す。
1782  * aliasnameがクエリ中に複数回指定された場合は、-1を返す。
1783  */
1784 static int
1785 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1786                                          const char *str)
1787 {
1788         int             i;
1789         Index   found = 0;
1790
1791         for (i = 1; i < root->simple_rel_array_size; i++)
1792         {
1793                 ListCell   *l;
1794
1795                 if (root->simple_rel_array[i] == NULL)
1796                         continue;
1797
1798                 Assert(i == root->simple_rel_array[i]->relid);
1799
1800                 if (RelnameCmp(&aliasname,
1801                                            &root->simple_rte_array[i]->eref->aliasname) != 0)
1802                         continue;
1803
1804                 foreach(l, initial_rels)
1805                 {
1806                         RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1807
1808                         if (rel->reloptkind == RELOPT_BASEREL)
1809                         {
1810                                 if (rel->relid != i)
1811                                         continue;
1812                         }
1813                         else
1814                         {
1815                                 Assert(rel->reloptkind == RELOPT_JOINREL);
1816
1817                                 if (!bms_is_member(i, rel->relids))
1818                                         continue;
1819                         }
1820
1821                         if (found != 0)
1822                         {
1823                                 parse_ereport(str,
1824                                                           ("Relation name \"%s\" is ambiguous.",
1825                                                            aliasname));
1826                                 return -1;
1827                         }
1828
1829                         found = i;
1830                         break;
1831                 }
1832
1833         }
1834
1835         return found;
1836 }
1837
1838 /*
1839  * relidビットマスクと一致するヒントを探す
1840  */
1841 static JoinMethodHint *
1842 find_join_hint(Relids joinrelids)
1843 {
1844         List       *join_hint;
1845         ListCell   *l;
1846
1847         join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1848
1849         foreach(l, join_hint)
1850         {
1851                 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1852
1853                 if (bms_equal(joinrelids, hint->joinrelids))
1854                         return hint;
1855         }
1856
1857         return NULL;
1858 }
1859
1860 /*
1861  * 結合方式のヒントを使用しやすい構造に変換する。
1862  */
1863 static void
1864 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
1865                 List *initial_rels, JoinMethodHint **join_method_hints)
1866 {
1867         int                             i;
1868         int                             relid;
1869         LeadingHint        *lhint;
1870         Relids                  joinrelids;
1871         int                             njoinrels;
1872         ListCell           *l;
1873
1874         for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1875         {
1876                 JoinMethodHint *hint = hstate->join_hints[i];
1877                 int     j;
1878
1879                 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1880                         continue;
1881
1882                 bms_free(hint->joinrelids);
1883                 hint->joinrelids = NULL;
1884                 relid = 0;
1885                 for (j = 0; j < hint->nrels; j++)
1886                 {
1887                         char   *relname = hint->relnames[j];
1888
1889                         relid = find_relid_aliasname(root, relname, initial_rels,
1890                                                                                  hint->base.hint_str);
1891
1892                         if (relid == -1)
1893                                 hint->base.state = HINT_STATE_ERROR;
1894
1895                         if (relid <= 0)
1896                                 break;
1897
1898                         if (bms_is_member(relid, hint->joinrelids))
1899                         {
1900                                 parse_ereport(hint->base.hint_str,
1901                                                           ("Relation name \"%s\" is duplicated.", relname));
1902                                 hint->base.state = HINT_STATE_ERROR;
1903                                 break;
1904                         }
1905
1906                         hint->joinrelids = bms_add_member(hint->joinrelids, relid);
1907                 }
1908
1909                 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
1910                         continue;
1911
1912                 hstate->join_hint_level[hint->nrels] =
1913                         lappend(hstate->join_hint_level[hint->nrels], hint);
1914         }
1915
1916         /*
1917          * 有効なLeading ヒントが指定されている場合は、結合順にあわせて join method
1918          * hint のフォーマットに変換する。
1919          */
1920         if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
1921                 return;
1922
1923         lhint = hstate->leading_hint;
1924         if (!hint_state_enabled(lhint))
1925                 return;
1926
1927         /* Leading hint は、全ての join 方式が有効な hint として登録する */
1928         joinrelids = NULL;
1929         njoinrels = 0;
1930         foreach(l, lhint->relations)
1931         {
1932                 char   *relname = (char *)lfirst(l);
1933                 JoinMethodHint *hint;
1934
1935                 relid =
1936                         find_relid_aliasname(root, relname, initial_rels,
1937                                                                  hstate->hint_str);
1938
1939                 if (relid == -1)
1940                 {
1941                         bms_free(joinrelids);
1942                         return;
1943                 }
1944
1945                 if (relid == 0)
1946                         continue;
1947
1948                 if (bms_is_member(relid, joinrelids))
1949                 {
1950                         parse_ereport(lhint->base.hint_str,
1951                                                   ("Relation name \"%s\" is duplicated.", relname));
1952                         lhint->base.state = HINT_STATE_ERROR;
1953                         bms_free(joinrelids);
1954                         return;
1955                 }
1956
1957                 joinrelids = bms_add_member(joinrelids, relid);
1958                 njoinrels++;
1959
1960                 if (njoinrels < 2)
1961                         continue;
1962
1963                 hint = find_join_hint(joinrelids);
1964                 if (hint == NULL)
1965                 {
1966                         /*
1967                          * Here relnames is not set, since Relids bitmap is sufficient to
1968                          * control paths of this query afterwards.
1969                          */
1970                         hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
1971                                                                                                                    HINT_LEADING);
1972                         hint->base.state = HINT_STATE_USED;
1973                         hint->nrels = njoinrels;
1974                         hint->enforce_mask = ENABLE_ALL_JOIN;
1975                         hint->joinrelids = bms_copy(joinrelids);
1976                 }
1977
1978                 join_method_hints[njoinrels] = hint;
1979
1980                 if (njoinrels >= nbaserel)
1981                         break;
1982         }
1983
1984         bms_free(joinrelids);
1985
1986         if (njoinrels < 2)
1987                 return;
1988
1989         for (i = 2; i <= njoinrels; i++)
1990         {
1991                 /* Leading で指定した組み合わせ以外の join hint を削除する */
1992                 list_free(hstate->join_hint_level[i]);
1993
1994                 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
1995         }
1996
1997         if (hint_state_enabled(lhint))
1998                 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
1999
2000         lhint->base.state = HINT_STATE_USED;
2001
2002 }
2003
2004 /*
2005  * set_plain_rel_pathlist
2006  *        Build access paths for a plain relation (no subquery, no inheritance)
2007  *
2008  * This function was copied and edited from set_plain_rel_pathlist() in
2009  * src/backend/optimizer/path/allpaths.c
2010  */
2011 static void
2012 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2013 {
2014         /* Consider sequential scan */
2015         add_path(rel, create_seqscan_path(root, rel));
2016
2017         /* Consider index scans */
2018         create_index_paths(root, rel);
2019
2020         /* Consider TID scans */
2021         create_tidscan_paths(root, rel);
2022
2023         /* Now find the cheapest of the paths for this rel */
2024         set_cheapest(rel);
2025 }
2026
2027 static void
2028 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2029                                   List *initial_rels)
2030 {
2031         ListCell   *l;
2032
2033         foreach(l, initial_rels)
2034         {
2035                 RelOptInfo         *rel = (RelOptInfo *) lfirst(l);
2036                 RangeTblEntry  *rte;
2037                 ScanMethodHint *hint;
2038
2039                 /*
2040                  * スキャン方式が選択できるリレーションのみ、スキャンパスを再生成する。
2041                  */
2042                 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2043                         continue;
2044
2045                 rte = root->simple_rte_array[rel->relid];
2046
2047                 /* 外部表はスキャン方式が選択できない。 */
2048                 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2049                         continue;
2050
2051                 /*
2052                  * scan method hint が指定されていなければ、初期値のGUCパラメータでscan
2053                  * path を再生成する。
2054                  */
2055                 if ((hint = find_scan_hint(root, rel)) == NULL)
2056                         set_scan_config_options(hstate->init_scan_mask,
2057                                                                         hstate->context);
2058                 else
2059                 {
2060                         set_scan_config_options(hint->enforce_mask, hstate->context);
2061                         hint->base.state = HINT_STATE_USED;
2062                 }
2063
2064                 list_free_deep(rel->pathlist);
2065                 rel->pathlist = NIL;
2066                 if (rte->inh)
2067                 {
2068                         /* It's an "append relation", process accordingly */
2069                         set_append_rel_pathlist(root, rel, rel->relid, rte);
2070                 }
2071                 else
2072                 {
2073                         set_plain_rel_pathlist(root, rel, rte);
2074                 }
2075         }
2076
2077         /*
2078          * Restore the GUC variables we set above.
2079          */
2080         set_scan_config_options(hstate->init_scan_mask, hstate->context);
2081 }
2082
2083 /*
2084  * make_join_rel() をラップする関数
2085  *
2086  * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
2087  * 呼び出す。
2088  */
2089 static RelOptInfo *
2090 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2091 {
2092         Relids                  joinrelids;
2093         JoinMethodHint *hint;
2094         RelOptInfo         *rel;
2095         int                             save_nestlevel;
2096
2097         joinrelids = bms_union(rel1->relids, rel2->relids);
2098         hint = find_join_hint(joinrelids);
2099         bms_free(joinrelids);
2100
2101         if (!hint)
2102                 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2103
2104         save_nestlevel = NewGUCNestLevel();
2105
2106         set_join_config_options(hint->enforce_mask, current_hint->context);
2107
2108         rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2109         hint->base.state = HINT_STATE_USED;
2110
2111         /*
2112          * Restore the GUC variables we set above.
2113          */
2114         AtEOXact_GUC(true, save_nestlevel);
2115
2116         return rel;
2117 }
2118
2119 static int
2120 get_num_baserels(List *initial_rels)
2121 {
2122         int                     nbaserel = 0;
2123         ListCell   *l;
2124
2125         foreach(l, initial_rels)
2126         {
2127                 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2128
2129                 if (rel->reloptkind == RELOPT_BASEREL)
2130                         nbaserel++;
2131                 else if (rel->reloptkind ==RELOPT_JOINREL)
2132                         nbaserel+= bms_num_members(rel->relids);
2133                 else
2134                 {
2135                         /* other values not expected here */
2136                         elog(ERROR, "Unrecognized reloptkind type: %d", rel->reloptkind);
2137                 }
2138         }
2139
2140         return nbaserel;
2141 }
2142
2143 static RelOptInfo *
2144 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2145                                                  List *initial_rels)
2146 {
2147         JoinMethodHint **join_method_hints;
2148         int                     nbaserel;
2149         RelOptInfo *rel;
2150         int                     i;
2151
2152         /*
2153          * pg_hint_planが無効、または有効なヒントが1つも指定されなかった場合は、標準
2154          * の処理を行う。
2155          */
2156         if (!current_hint)
2157         {
2158                 if (prev_join_search)
2159                         return (*prev_join_search) (root, levels_needed, initial_rels);
2160                 else if (enable_geqo && levels_needed >= geqo_threshold)
2161                         return geqo(root, levels_needed, initial_rels);
2162                 else
2163                         return standard_join_search(root, levels_needed, initial_rels);
2164         }
2165
2166         /* We apply scan method hint rebuild scan path. */
2167         rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2168
2169         /*
2170          * GEQOを使用する条件を満たした場合は、GEQOを用いた結合方式の検索を行う。
2171          * このとき、スキャン方式のヒントとSetヒントのみが有効になり、結合方式や結合
2172          * 順序はヒント句は無効になりGEQOのアルゴリズムで決定される。
2173          */
2174         if (enable_geqo && levels_needed >= geqo_threshold)
2175                 return geqo(root, levels_needed, initial_rels);
2176
2177         nbaserel = get_num_baserels(initial_rels);
2178         current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2179         join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2180
2181         transform_join_hints(current_hint, root, nbaserel, initial_rels,
2182                                                  join_method_hints);
2183
2184         rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2185
2186         for (i = 2; i <= nbaserel; i++)
2187         {
2188                 list_free(current_hint->join_hint_level[i]);
2189
2190                 /* free Leading hint only */
2191                 if (join_method_hints[i] != NULL &&
2192                         join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2193                         JoinMethodHintDelete(join_method_hints[i]);
2194         }
2195         pfree(current_hint->join_hint_level);
2196         pfree(join_method_hints);
2197
2198         if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2199                 hint_state_enabled(current_hint->leading_hint))
2200                 set_join_config_options(current_hint->init_join_mask,
2201                                                                 current_hint->context);
2202
2203         return rel;
2204 }
2205
2206 /*
2207  * set_rel_pathlist
2208  *        Build access paths for a base relation
2209  *
2210  * This function was copied and edited from set_rel_pathlist() in
2211  * src/backend/optimizer/path/allpaths.c
2212  */
2213 static void
2214 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2215                                  Index rti, RangeTblEntry *rte)
2216 {
2217         if (rte->inh)
2218         {
2219                 /* It's an "append relation", process accordingly */
2220                 set_append_rel_pathlist(root, rel, rti, rte);
2221         }
2222         else
2223         {
2224                 if (rel->rtekind == RTE_RELATION)
2225                 {
2226                         if (rte->relkind == RELKIND_RELATION)
2227                         {
2228                                 /* Plain relation */
2229                                 set_plain_rel_pathlist(root, rel, rte);
2230                         }
2231                         else
2232                                 elog(ERROR, "Unexpected relkind: %c", rte->relkind);
2233                 }
2234                 else
2235                         elog(ERROR, "Unexpected rtekind: %d", (int) rel->rtekind);
2236         }
2237 }
2238
2239 #define standard_join_search pg_hint_plan_standard_join_search
2240 #define join_search_one_level pg_hint_plan_join_search_one_level
2241 #define make_join_rel make_join_rel_wrapper
2242 #include "core.c"
2243
2244 #undef make_join_rel
2245 #define make_join_rel pg_hint_plan_make_join_rel
2246 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2247 do { \
2248         ScanMethodHint *hint = NULL; \
2249         if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2250         { \
2251                 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2252                 hint->base.state = HINT_STATE_USED; \
2253         } \
2254         add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2255         if (hint != NULL) \
2256                 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2257 } while(0)
2258 #include "make_join_rel.c"