OSDN Git Service

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