OSDN Git Service

エラーメッセージのクリーンアップに伴って使用しなくなった変数を削除した。
[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_hint = 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 /* Hold reference to currently active hint */
343 static HintState *current_hint = NULL;
344
345 /*
346  * List of hint contexts.  We treat the head of the list as the Top of the
347  * context stack, so current_hint always points the first element of this list.
348  */
349 static List *HintStateStack = NIL;
350
351 /*
352  * Holds statement name during executing EXECUTE command.  NULL for other
353  * statements.
354  */
355 static char        *stmt_name = NULL;
356
357 static const HintParser parsers[] = {
358         {HINT_SEQSCAN, ScanMethodHintCreate},
359         {HINT_INDEXSCAN, ScanMethodHintCreate},
360         {HINT_BITMAPSCAN, ScanMethodHintCreate},
361         {HINT_TIDSCAN, ScanMethodHintCreate},
362         {HINT_NOSEQSCAN, ScanMethodHintCreate},
363         {HINT_NOINDEXSCAN, ScanMethodHintCreate},
364         {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
365         {HINT_NOTIDSCAN, ScanMethodHintCreate},
366 #if PG_VERSION_NUM >= 90200
367         {HINT_INDEXONLYSCAN, ScanMethodHintCreate},
368         {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate},
369 #endif
370         {HINT_NESTLOOP, JoinMethodHintCreate},
371         {HINT_MERGEJOIN, JoinMethodHintCreate},
372         {HINT_HASHJOIN, JoinMethodHintCreate},
373         {HINT_NONESTLOOP, JoinMethodHintCreate},
374         {HINT_NOMERGEJOIN, JoinMethodHintCreate},
375         {HINT_NOHASHJOIN, JoinMethodHintCreate},
376         {HINT_LEADING, LeadingHintCreate},
377         {HINT_SET, SetHintCreate},
378         {NULL, NULL}
379 };
380
381 /*
382  * Module load callbacks
383  */
384 void
385 _PG_init(void)
386 {
387         /* Define custom GUC variables. */
388         DefineCustomBoolVariable("pg_hint_plan.enable_hint",
389                          "Force planner to use plans specified in the hint comment preceding to the query.",
390                                                          NULL,
391                                                          &pg_hint_plan_enable_hint,
392                                                          true,
393                                                          PGC_USERSET,
394                                                          0,
395                                                          NULL,
396                                                          NULL,
397                                                          NULL);
398
399         DefineCustomBoolVariable("pg_hint_plan.debug_print",
400                                                          "Logs results of hint parsing.",
401                                                          NULL,
402                                                          &pg_hint_plan_debug_print,
403                                                          false,
404                                                          PGC_USERSET,
405                                                          0,
406                                                          NULL,
407                                                          NULL,
408                                                          NULL);
409
410         DefineCustomEnumVariable("pg_hint_plan.parse_messages",
411                                                          "Message level of parse errors.",
412                                                          NULL,
413                                                          &pg_hint_plan_parse_messages,
414                                                          INFO,
415                                                          parse_messages_level_options,
416                                                          PGC_USERSET,
417                                                          0,
418                                                          NULL,
419                                                          NULL,
420                                                          NULL);
421
422         /* Install hooks. */
423         prev_ProcessUtility = ProcessUtility_hook;
424         ProcessUtility_hook = pg_hint_plan_ProcessUtility;
425         prev_planner = planner_hook;
426         planner_hook = pg_hint_plan_planner;
427         prev_get_relation_info = get_relation_info_hook;
428         get_relation_info_hook = pg_hint_plan_get_relation_info;
429         prev_join_search = join_search_hook;
430         join_search_hook = pg_hint_plan_join_search;
431 }
432
433 /*
434  * Module unload callback
435  * XXX never called
436  */
437 void
438 _PG_fini(void)
439 {
440         /* Uninstall hooks. */
441         ProcessUtility_hook = prev_ProcessUtility;
442         planner_hook = prev_planner;
443         get_relation_info_hook = prev_get_relation_info;
444         join_search_hook = prev_join_search;
445 }
446
447 /*
448  * create and delete functions the hint object
449  */
450
451 static Hint *
452 ScanMethodHintCreate(const char *hint_str, const char *keyword)
453 {
454         ScanMethodHint *hint;
455
456         hint = palloc(sizeof(ScanMethodHint));
457         hint->base.hint_str = hint_str;
458         hint->base.keyword = keyword;
459         hint->base.type = HINT_TYPE_SCAN_METHOD;
460         hint->base.state = HINT_STATE_NOTUSED;
461         hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
462         hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
463         hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
464         hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
465         hint->relname = NULL;
466         hint->indexnames = NIL;
467         hint->enforce_mask = 0;
468
469         return (Hint *) hint;
470 }
471
472 static void
473 ScanMethodHintDelete(ScanMethodHint *hint)
474 {
475         if (!hint)
476                 return;
477
478         if (hint->relname)
479                 pfree(hint->relname);
480         list_free_deep(hint->indexnames);
481         pfree(hint);
482 }
483
484 static Hint *
485 JoinMethodHintCreate(const char *hint_str, const char *keyword)
486 {
487         JoinMethodHint *hint;
488
489         hint = palloc(sizeof(JoinMethodHint));
490         hint->base.hint_str = hint_str;
491         hint->base.keyword = keyword;
492         hint->base.type = HINT_TYPE_JOIN_METHOD;
493         hint->base.state = HINT_STATE_NOTUSED;
494         hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
495         hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
496         hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
497         hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
498         hint->nrels = 0;
499         hint->relnames = NULL;
500         hint->enforce_mask = 0;
501         hint->joinrelids = NULL;
502
503         return (Hint *) hint;
504 }
505
506 static void
507 JoinMethodHintDelete(JoinMethodHint *hint)
508 {
509         if (!hint)
510                 return;
511
512         if (hint->relnames)
513         {
514                 int     i;
515
516                 for (i = 0; i < hint->nrels; i++)
517                         pfree(hint->relnames[i]);
518                 pfree(hint->relnames);
519         }
520         bms_free(hint->joinrelids);
521         pfree(hint);
522 }
523
524 static Hint *
525 LeadingHintCreate(const char *hint_str, const char *keyword)
526 {
527         LeadingHint        *hint;
528
529         hint = palloc(sizeof(LeadingHint));
530         hint->base.hint_str = hint_str;
531         hint->base.keyword = keyword;
532         hint->base.type = HINT_TYPE_LEADING;
533         hint->base.state = HINT_STATE_NOTUSED;
534         hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
535         hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
536         hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
537         hint->base.parser_func = (HintParseFunction) LeadingHintParse;
538         hint->relations = NIL;
539
540         return (Hint *) hint;
541 }
542
543 static void
544 LeadingHintDelete(LeadingHint *hint)
545 {
546         if (!hint)
547                 return;
548
549         list_free_deep(hint->relations);
550         pfree(hint);
551 }
552
553 static Hint *
554 SetHintCreate(const char *hint_str, const char *keyword)
555 {
556         SetHint    *hint;
557
558         hint = palloc(sizeof(SetHint));
559         hint->base.hint_str = hint_str;
560         hint->base.keyword = keyword;
561         hint->base.type = HINT_TYPE_SET;
562         hint->base.state = HINT_STATE_NOTUSED;
563         hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
564         hint->base.dump_func = (HintDumpFunction) SetHintDump;
565         hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
566         hint->base.parser_func = (HintParseFunction) SetHintParse;
567         hint->name = NULL;
568         hint->value = NULL;
569
570         return (Hint *) hint;
571 }
572
573 static void
574 SetHintDelete(SetHint *hint)
575 {
576         if (!hint)
577                 return;
578
579         if (hint->name)
580                 pfree(hint->name);
581         if (hint->value)
582                 pfree(hint->value);
583         pfree(hint);
584 }
585
586 static HintState *
587 HintStateCreate(void)
588 {
589         HintState   *hstate;
590
591         hstate = palloc(sizeof(HintState));
592         hstate->hint_str = NULL;
593         hstate->nall_hints = 0;
594         hstate->max_all_hints = 0;
595         hstate->all_hints = NULL;
596         memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
597         hstate->scan_hints = NULL;
598         hstate->init_scan_mask = 0;
599         hstate->parent_relid = 0;
600         hstate->parent_hint = NULL;
601         hstate->join_hints = NULL;
602         hstate->init_join_mask = 0;
603         hstate->join_hint_level = NULL;
604         hstate->leading_hint = NULL;
605         hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
606         hstate->set_hints = NULL;
607
608         return hstate;
609 }
610
611 static void
612 HintStateDelete(HintState *hstate)
613 {
614         int                     i;
615
616         if (!hstate)
617                 return;
618
619         if (hstate->hint_str)
620                 pfree(hstate->hint_str);
621
622         for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
623                 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
624         if (hstate->all_hints)
625                 pfree(hstate->all_hints);
626 }
627
628 /*
629  * dump functions
630  */
631
632 static void
633 dump_quote_value(StringInfo buf, const char *value)
634 {
635         bool            need_quote = false;
636         const char *str;
637
638         for (str = value; *str != '\0'; str++)
639         {
640                 if (isspace(*str) || *str == ')' || *str == '"')
641                 {
642                         need_quote = true;
643                         appendStringInfoCharMacro(buf, '"');
644                         break;
645                 }
646         }
647
648         for (str = value; *str != '\0'; str++)
649         {
650                 if (*str == '"')
651                         appendStringInfoCharMacro(buf, '"');
652
653                 appendStringInfoCharMacro(buf, *str);
654         }
655
656         if (need_quote)
657                 appendStringInfoCharMacro(buf, '"');
658 }
659
660 static void
661 ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
662 {
663         ListCell   *l;
664
665         appendStringInfo(buf, "%s(", hint->base.keyword);
666         dump_quote_value(buf, hint->relname);
667         foreach(l, hint->indexnames)
668         {
669                 appendStringInfoCharMacro(buf, ' ');
670                 dump_quote_value(buf, (char *) lfirst(l));
671         }
672         appendStringInfoString(buf, ")\n");
673 }
674
675 static void
676 JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
677 {
678         int     i;
679
680         appendStringInfo(buf, "%s(", hint->base.keyword);
681         dump_quote_value(buf, hint->relnames[0]);
682         for (i = 1; i < hint->nrels; i++)
683         {
684                 appendStringInfoCharMacro(buf, ' ');
685                 dump_quote_value(buf, hint->relnames[i]);
686         }
687         appendStringInfoString(buf, ")\n");
688
689 }
690
691 static void
692 LeadingHintDump(LeadingHint *hint, StringInfo buf)
693 {
694         bool            is_first;
695         ListCell   *l;
696
697         appendStringInfo(buf, "%s(", HINT_LEADING);
698         is_first = true;
699         foreach(l, hint->relations)
700         {
701                 if (is_first)
702                         is_first = false;
703                 else
704                         appendStringInfoCharMacro(buf, ' ');
705
706                 dump_quote_value(buf, (char *) lfirst(l));
707         }
708
709         appendStringInfoString(buf, ")\n");
710 }
711
712 static void
713 SetHintDump(SetHint *hint, StringInfo buf)
714 {
715         appendStringInfo(buf, "%s(", HINT_SET);
716         dump_quote_value(buf, hint->name);
717         appendStringInfoCharMacro(buf, ' ');
718         dump_quote_value(buf, hint->value);
719         appendStringInfo(buf, ")\n");
720 }
721
722 static void
723 all_hint_dump(HintState *hstate, StringInfo buf, const char *title,
724                           HintStatus state)
725 {
726         int     i;
727
728         appendStringInfo(buf, "%s:\n", title);
729         for (i = 0; i < hstate->nall_hints; i++)
730         {
731                 if (hstate->all_hints[i]->state != state)
732                         continue;
733
734                 hstate->all_hints[i]->dump_func(hstate->all_hints[i], buf);
735         }
736 }
737
738 static void
739 HintStateDump(HintState *hstate)
740 {
741         StringInfoData  buf;
742
743         if (!hstate)
744         {
745                 elog(LOG, "pg_hint_plan:\nno hint");
746                 return;
747         }
748
749         initStringInfo(&buf);
750
751         appendStringInfoString(&buf, "pg_hint_plan:\n");
752         all_hint_dump(hstate, &buf, "used hint", HINT_STATE_USED);
753         all_hint_dump(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
754         all_hint_dump(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
755         all_hint_dump(hstate, &buf, "error hint", HINT_STATE_ERROR);
756
757         elog(LOG, "%s", buf.data);
758
759         pfree(buf.data);
760 }
761
762 /*
763  * compare functions
764  */
765
766 static int
767 RelnameCmp(const void *a, const void *b)
768 {
769         const char *relnamea = *((const char **) a);
770         const char *relnameb = *((const char **) b);
771
772         return strcmp(relnamea, relnameb);
773 }
774
775 static int
776 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
777 {
778         return RelnameCmp(&a->relname, &b->relname);
779 }
780
781 static int
782 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
783 {
784         int     i;
785
786         if (a->nrels != b->nrels)
787                 return a->nrels - b->nrels;
788
789         for (i = 0; i < a->nrels; i++)
790         {
791                 int     result;
792                 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
793                         return result;
794         }
795
796         return 0;
797 }
798
799 static int
800 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
801 {
802         return 0;
803 }
804
805 static int
806 SetHintCmp(const SetHint *a, const SetHint *b)
807 {
808         return strcmp(a->name, b->name);
809 }
810
811 static int
812 HintCmp(const void *a, const void *b)
813 {
814         const Hint *hinta = *((const Hint **) a);
815         const Hint *hintb = *((const Hint **) b);
816
817         if (hinta->type != hintb->type)
818                 return hinta->type - hintb->type;
819
820         return hinta->cmp_func(hinta, hintb);
821 }
822
823 /*
824  * Returns byte offset of hint b from hint a.  If hint a was specified before
825  * b, positive value is returned.
826  */
827 static int
828 HintCmpWithPos(const void *a, const void *b)
829 {
830         const Hint *hinta = *((const Hint **) a);
831         const Hint *hintb = *((const Hint **) b);
832         int             result;
833
834         result = HintCmp(a, b);
835         if (result == 0)
836                 result = hinta->hint_str - hintb->hint_str;
837
838         return result;
839 }
840
841 /*
842  * parse functions
843  */
844 static const char *
845 parse_keyword(const char *str, StringInfo buf)
846 {
847         skip_space(str);
848
849         while (!isspace(*str) && *str != '(' && *str != '\0')
850                 appendStringInfoCharMacro(buf, *str++);
851
852         return str;
853 }
854
855 static const char *
856 skip_opened_parenthesis(const char *str)
857 {
858         skip_space(str);
859
860         if (*str != '(')
861         {
862                 parse_ereport(str, ("Opening parenthesis is necessary."));
863                 return NULL;
864         }
865
866         str++;
867
868         return str;
869 }
870
871 static const char *
872 skip_closed_parenthesis(const char *str)
873 {
874         skip_space(str);
875
876         if (*str != ')')
877         {
878                 parse_ereport(str, ("Closing parenthesis is necessary."));
879                 return NULL;
880         }
881
882         str++;
883
884         return str;
885 }
886
887 /*
888  * Parse a token from str, and store malloc'd copy into word.  A token can be
889  * quoted with '"'.  Return value is pointer to unparsed portion of original
890  * string, or NULL if an error occurred.
891  *
892  * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
893  */
894 static const char *
895 parse_quote_value(const char *str, char **word, bool truncate)
896 {
897         StringInfoData  buf;
898         bool                    in_quote;
899
900         /* Skip leading spaces. */
901         skip_space(str);
902
903         initStringInfo(&buf);
904         if (*str == '"')
905         {
906                 str++;
907                 in_quote = true;
908         }
909         else
910                 in_quote = false;
911
912         while (true)
913         {
914                 if (in_quote)
915                 {
916                         /* Double quotation must be closed. */
917                         if (*str == '\0')
918                         {
919                                 pfree(buf.data);
920                                 parse_ereport(str, ("Unterminated quoted string."));
921                                 return NULL;
922                         }
923
924                         /*
925                          * Skip escaped double quotation.
926                          * 
927                          * We don't allow slash-asterisk and asterisk-slash (delimiters of
928                          * block comments) to be an object name, so users must specify
929                          * alias for such object names.
930                          *
931                          * Those special names can be allowed if we care escaped slashes
932                          * and asterisks, but we don't.
933                          */
934                         if (*str == '"')
935                         {
936                                 str++;
937                                 if (*str != '"')
938                                         break;
939                         }
940                 }
941                 else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
942                         break;
943
944                 appendStringInfoCharMacro(&buf, *str++);
945         }
946
947         if (buf.len == 0)
948         {
949                 parse_ereport(str, ("Zero-length delimited string."));
950
951                 pfree(buf.data);
952
953                 return NULL;
954         }
955
956         /* Truncate name if it's too long */
957         if (truncate)
958                 truncate_identifier(buf.data, strlen(buf.data), true);
959
960         *word = buf.data;
961
962         return str;
963 }
964
965 static void
966 parse_hints(HintState *hstate, Query *parse, const char *str)
967 {
968         StringInfoData  buf;
969         char               *head;
970
971         initStringInfo(&buf);
972         while (*str != '\0')
973         {
974                 const HintParser *parser;
975
976                 /* in error message, we output the comment including the keyword. */
977                 head = (char *) str;
978
979                 /* parse only the keyword of the hint. */
980                 resetStringInfo(&buf);
981                 str = parse_keyword(str, &buf);
982
983                 for (parser = parsers; parser->keyword != NULL; parser++)
984                 {
985                         char   *keyword = parser->keyword;
986                         Hint   *hint;
987
988                         if (strcasecmp(buf.data, keyword) != 0)
989                                 continue;
990
991                         hint = parser->create_func(head, keyword);
992
993                         /* parser of each hint does parse in a parenthesis. */
994                         if ((str = skip_opened_parenthesis(str)) == NULL ||
995                                 (str = hint->parser_func(hint, hstate, parse, str)) == NULL ||
996                                 (str = skip_closed_parenthesis(str)) == NULL)
997                         {
998                                 hint->delete_func(hint);
999                                 pfree(buf.data);
1000                                 return;
1001                         }
1002
1003                         /*
1004                          * Add hint information into all_hints array.  If we don't have
1005                          * enough space, double the array.
1006                          */
1007                         if (hstate->nall_hints == 0)
1008                         {
1009                                 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1010                                 hstate->all_hints = (Hint **)
1011                                         palloc(sizeof(Hint *) * hstate->max_all_hints);
1012                         }
1013                         else if (hstate->nall_hints == hstate->max_all_hints)
1014                         {
1015                                 hstate->max_all_hints *= 2;
1016                                 hstate->all_hints = (Hint **)
1017                                         repalloc(hstate->all_hints,
1018                                                          sizeof(Hint *) * hstate->max_all_hints);
1019                         }
1020
1021                         hstate->all_hints[hstate->nall_hints] = hint;
1022                         hstate->nall_hints++;
1023
1024                         skip_space(str);
1025
1026                         break;
1027                 }
1028
1029                 if (parser->keyword == NULL)
1030                 {
1031                         parse_ereport(head,
1032                                                   ("Unrecognized hint keyword \"%s\".", buf.data));
1033                         pfree(buf.data);
1034                         return;
1035                 }
1036         }
1037
1038         pfree(buf.data);
1039 }
1040
1041 /*
1042  * Do basic parsing of the query head comment.
1043  */
1044 static HintState *
1045 parse_head_comment(Query *parse)
1046 {
1047         const char *p;
1048         char       *head;
1049         char       *tail;
1050         int                     len;
1051         int                     i;
1052         HintState   *hstate;
1053
1054         /* get client-supplied query string. */
1055         if (stmt_name)
1056         {
1057                 PreparedStatement  *entry;
1058
1059                 entry = FetchPreparedStatement(stmt_name, true);
1060                 p = entry->plansource->query_string;
1061         }
1062         else
1063                 p = debug_query_string;
1064
1065         if (p == NULL)
1066                 return NULL;
1067
1068         /* extract query head comment. */
1069         len = strlen(HINT_START);
1070         skip_space(p);
1071         if (strncmp(p, HINT_START, len))
1072                 return NULL;
1073
1074         head = (char *) p;
1075         p += len;
1076         skip_space(p);
1077
1078         /* find hint end keyword. */
1079         if ((tail = strstr(p, HINT_END)) == NULL)
1080         {
1081                 parse_ereport(head, ("Unterminated block comment."));
1082                 return NULL;
1083         }
1084
1085         /* We don't support nested block comments. */
1086         if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1087         {
1088                 parse_ereport(head, ("Nested block comments are not supported."));
1089                 return NULL;
1090         }
1091
1092         /* Make a copy of hint. */
1093         len = tail - p;
1094         head = palloc(len + 1);
1095         memcpy(head, p, len);
1096         head[len] = '\0';
1097         p = head;
1098
1099         hstate = HintStateCreate();
1100         hstate->hint_str = head;
1101
1102         /* parse each hint. */
1103         parse_hints(hstate, parse, p);
1104
1105         /* When nothing specified a hint, we free HintState and returns NULL. */
1106         if (hstate->nall_hints == 0)
1107         {
1108                 HintStateDelete(hstate);
1109                 return NULL;
1110         }
1111
1112         /* Sort hints in order of original position. */
1113         qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1114                   HintCmpWithPos);
1115
1116         /*
1117          * If we have hints which are specified for an object, mark preceding one
1118          * as 'duplicated' to ignore it in planner phase.
1119          */
1120         for (i = 0; i < hstate->nall_hints; i++)
1121         {
1122                 Hint   *cur_hint = hstate->all_hints[i];
1123                 Hint   *next_hint;
1124
1125                 /* Count up hints per hint-type. */
1126                 hstate->num_hints[cur_hint->type]++;
1127
1128                 /* If we don't have next, nothing to compare. */
1129                 if (i + 1 >= hstate->nall_hints)
1130                         break;
1131                 next_hint = hstate->all_hints[i + 1];
1132
1133                 /*
1134                  * We need to pass address of hint pointers, because HintCmp has
1135                  * been designed to be used with qsort.
1136                  */
1137                 if (HintCmp(&cur_hint, &next_hint) == 0)
1138                 {
1139                         parse_ereport(cur_hint->hint_str,
1140                                                   ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1141                         cur_hint->state = HINT_STATE_DUPLICATION;
1142                 }
1143         }
1144
1145         /*
1146          * Make sure that per-type array pointers point proper position in the
1147          * array which consists of all hints.
1148          */
1149         hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1150         hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1151                 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1152         hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1153                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1154                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1155                 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1156         hstate->set_hints = (SetHint **) hstate->all_hints +
1157                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1158                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1159                 hstate->num_hints[HINT_TYPE_LEADING];
1160
1161         return hstate;
1162 }
1163
1164 /*
1165  * Parse inside of parentheses of scan-method hints.
1166  */
1167 static const char *
1168 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1169                                         const char *str)
1170 {
1171         const char *keyword = hint->base.keyword;
1172
1173         /* Given hint is invalid if relation name can't be parsed. */
1174         if ((str = parse_quote_value(str, &hint->relname, true))
1175                 == NULL)
1176                 return NULL;
1177
1178         skip_space(str);
1179
1180         /* Parse index name(s) if given hint accepts. */
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, true);
1192                         if (str == NULL)
1193                                 return NULL;
1194
1195                         hint->indexnames = lappend(hint->indexnames, indexname);
1196                         skip_space(str);
1197                 }
1198         }
1199
1200         /* Set a bit for specified hint. */
1201         if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1202                 hint->enforce_mask = ENABLE_SEQSCAN;
1203         else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1204                 hint->enforce_mask = ENABLE_INDEXSCAN;
1205         else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1206                 hint->enforce_mask = ENABLE_BITMAPSCAN;
1207         else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1208                 hint->enforce_mask = ENABLE_TIDSCAN;
1209         else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1210                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1211         else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1212                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1213         else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1214                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1215         else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1216                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1217 #if PG_VERSION_NUM >= 90200
1218         else if (strcasecmp(keyword, HINT_INDEXONLYSCAN) == 0)
1219                 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1220         else if (strcasecmp(keyword, HINT_NOINDEXONLYSCAN) == 0)
1221                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1222 #endif
1223         else
1224         {
1225                 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1226                 return NULL;
1227         }
1228
1229         return str;
1230 }
1231
1232 static const char *
1233 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1234                                         const char *str)
1235 {
1236         char       *relname;
1237         const char *keyword = hint->base.keyword;
1238
1239         skip_space(str);
1240
1241         hint->relnames = palloc(sizeof(char *));
1242
1243         while ((str = parse_quote_value(str, &relname, true))
1244                    != NULL)
1245         {
1246                 hint->nrels++;
1247                 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1248                 hint->relnames[hint->nrels - 1] = relname;
1249
1250                 skip_space(str);
1251                 if (*str == ')')
1252                         break;
1253         }
1254
1255         if (str == NULL)
1256                 return NULL;
1257
1258         /* A join hint requires at least two relations to be specified. */
1259         if (hint->nrels < 2)
1260         {
1261                 parse_ereport(str,
1262                                           ("%s hint requires at least two relations.",
1263                                            hint->base.keyword));
1264                 hint->base.state = HINT_STATE_ERROR;
1265         }
1266
1267         /* Sort hints in alphabetical order of relation names. */
1268         qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1269
1270         if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1271                 hint->enforce_mask = ENABLE_NESTLOOP;
1272         else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1273                 hint->enforce_mask = ENABLE_MERGEJOIN;
1274         else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1275                 hint->enforce_mask = ENABLE_HASHJOIN;
1276         else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1277                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1278         else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1279                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1280         else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1281                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1282         else
1283         {
1284                 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1285                 return NULL;
1286         }
1287
1288         return str;
1289 }
1290
1291 static const char *
1292 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1293                                  const char *str)
1294 {
1295         skip_space(str);
1296
1297         while (*str != ')')
1298         {
1299                 char   *relname;
1300
1301                 if ((str = parse_quote_value(str, &relname, true))
1302                         == NULL)
1303                         return NULL;
1304
1305                 hint->relations = lappend(hint->relations, relname);
1306
1307                 skip_space(str);
1308         }
1309
1310         /* A Leading hint requires at least two relations to be specified. */
1311         if (list_length(hint->relations) < 2)
1312         {
1313                 parse_ereport(hint->base.hint_str,
1314                                           ("%s hint requires at least two relations.",
1315                                            HINT_LEADING));
1316                 hint->base.state = HINT_STATE_ERROR;
1317         }
1318
1319         return str;
1320 }
1321
1322 static const char *
1323 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1324 {
1325         if ((str = parse_quote_value(str, &hint->name, true))
1326                 == NULL ||
1327                 (str = parse_quote_value(str, &hint->value, false))
1328                 == NULL)
1329                 return NULL;
1330
1331         return str;
1332 }
1333
1334 /*
1335  * set GUC parameter functions
1336  */
1337
1338 static int
1339 set_config_option_wrapper(const char *name, const char *value,
1340                                                   GucContext context, GucSource source,
1341                                                   GucAction action, bool changeVal, int elevel)
1342 {
1343         int                             result = 0;
1344         MemoryContext   ccxt = CurrentMemoryContext;
1345
1346         PG_TRY();
1347         {
1348 #if PG_VERSION_NUM >= 90200
1349                 result = set_config_option(name, value, context, source,
1350                                                                    action, changeVal, 0);
1351 #else
1352                 result = set_config_option(name, value, context, source,
1353                                                                    action, changeVal);
1354 #endif
1355         }
1356         PG_CATCH();
1357         {
1358                 ErrorData          *errdata;
1359
1360                 /* Save error info */
1361                 MemoryContextSwitchTo(ccxt);
1362                 errdata = CopyErrorData();
1363                 FlushErrorState();
1364
1365                 ereport(elevel, (errcode(errdata->sqlerrcode),
1366                                 errmsg("%s", errdata->message),
1367                                 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1368                                 errdata->hint ? errhint("%s", errdata->hint) : 0));
1369                 FreeErrorData(errdata);
1370         }
1371         PG_END_TRY();
1372
1373         return result;
1374 }
1375
1376 static int
1377 set_config_options(SetHint **options, int noptions, GucContext context)
1378 {
1379         int     i;
1380         int     save_nestlevel;
1381
1382         save_nestlevel = NewGUCNestLevel();
1383
1384         for (i = 0; i < noptions; i++)
1385         {
1386                 SetHint    *hint = options[i];
1387                 int                     result;
1388
1389                 if (!hint_state_enabled(hint))
1390                         continue;
1391
1392                 result = set_config_option_wrapper(hint->name, hint->value, context,
1393                                                                                    PGC_S_SESSION, GUC_ACTION_SAVE, true,
1394                                                                                    pg_hint_plan_parse_messages);
1395                 if (result != 0)
1396                         hint->base.state = HINT_STATE_USED;
1397                 else
1398                         hint->base.state = HINT_STATE_ERROR;
1399         }
1400
1401         return save_nestlevel;
1402 }
1403
1404 #define SET_CONFIG_OPTION(name, type_bits) \
1405         set_config_option_wrapper((name), \
1406                 (mask & (type_bits)) ? "true" : "false", \
1407                 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1408
1409 static void
1410 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1411 {
1412         unsigned char   mask;
1413
1414         if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1415                 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1416 #if PG_VERSION_NUM >= 90200
1417                 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1418 #endif
1419                 )
1420                 mask = enforce_mask;
1421         else
1422                 mask = enforce_mask & current_hint->init_scan_mask;
1423
1424         SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1425         SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1426         SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1427         SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1428 #if PG_VERSION_NUM >= 90200
1429         SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1430 #endif
1431 }
1432
1433 static void
1434 set_join_config_options(unsigned char enforce_mask, GucContext context)
1435 {
1436         unsigned char   mask;
1437
1438         if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1439                 enforce_mask == ENABLE_HASHJOIN)
1440                 mask = enforce_mask;
1441         else
1442                 mask = enforce_mask & current_hint->init_join_mask;
1443
1444         SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1445         SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1446         SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1447 }
1448
1449 /*
1450  * pg_hint_plan hook functions
1451  */
1452
1453 static void
1454 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1455                                                         ParamListInfo params, bool isTopLevel,
1456                                                         DestReceiver *dest, char *completionTag)
1457 {
1458         Node                               *node;
1459
1460         if (!pg_hint_plan_enable_hint)
1461         {
1462                 if (prev_ProcessUtility)
1463                         (*prev_ProcessUtility) (parsetree, queryString, params,
1464                                                                         isTopLevel, dest, completionTag);
1465                 else
1466                         standard_ProcessUtility(parsetree, queryString, params,
1467                                                                         isTopLevel, dest, completionTag);
1468
1469                 return;
1470         }
1471
1472         node = parsetree;
1473         if (IsA(node, ExplainStmt))
1474         {
1475                 /*
1476                  * Draw out parse tree of actual query from Query struct of EXPLAIN
1477                  * statement.
1478                  */
1479                 ExplainStmt        *stmt;
1480                 Query              *query;
1481
1482                 stmt = (ExplainStmt *) node;
1483
1484                 Assert(IsA(stmt->query, Query));
1485                 query = (Query *) stmt->query;
1486
1487                 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1488                         node = query->utilityStmt;
1489         }
1490
1491         /*
1492          * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1493          * specified to preceding PREPARE command to use it as source of hints.
1494          */
1495         if (IsA(node, ExecuteStmt))
1496         {
1497                 ExecuteStmt        *stmt;
1498
1499                 stmt = (ExecuteStmt *) node;
1500                 stmt_name = stmt->name;
1501         }
1502 #if PG_VERSION_NUM >= 90200
1503         /*
1504          * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1505          * specially here.
1506          */
1507         if (IsA(node, CreateTableAsStmt))
1508         {
1509                 CreateTableAsStmt          *stmt;
1510                 Query              *query;
1511
1512                 stmt = (CreateTableAsStmt *) node;
1513                 Assert(IsA(stmt->query, Query));
1514                 query = (Query *) stmt->query;
1515
1516                 if (query->commandType == CMD_UTILITY &&
1517                         IsA(query->utilityStmt, ExecuteStmt))
1518                 {
1519                         ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1520                         stmt_name = estmt->name;
1521                 }
1522         }
1523 #endif
1524         if (stmt_name)
1525         {
1526                 PG_TRY();
1527                 {
1528                         if (prev_ProcessUtility)
1529                                 (*prev_ProcessUtility) (parsetree, queryString, params,
1530                                                                                 isTopLevel, dest, completionTag);
1531                         else
1532                                 standard_ProcessUtility(parsetree, queryString, params,
1533                                                                                 isTopLevel, dest, completionTag);
1534                 }
1535                 PG_CATCH();
1536                 {
1537                         stmt_name = NULL;
1538                         PG_RE_THROW();
1539                 }
1540                 PG_END_TRY();
1541
1542                 stmt_name = NULL;
1543
1544                 return;
1545         }
1546
1547         if (prev_ProcessUtility)
1548                 (*prev_ProcessUtility) (parsetree, queryString, params,
1549                                                                 isTopLevel, dest, completionTag);
1550         else
1551                 standard_ProcessUtility(parsetree, queryString, params,
1552                                                                 isTopLevel, dest, completionTag);
1553 }
1554
1555 /*
1556  * Push a hint into hint stack which is implemented with List struct.  Head of
1557  * list is top of stack.
1558  */
1559 static void
1560 push_hint(HintState *hstate)
1561 {
1562         /* Prepend new hint to the list means pushing to stack. */
1563         HintStateStack = lcons(hstate, HintStateStack);
1564
1565         /* Pushed hint is the one which should be used hereafter. */
1566         current_hint = hstate;
1567 }
1568
1569 /* Pop a hint from hint stack.  Popped hint is automatically discarded. */
1570 static void
1571 pop_hint(void)
1572 {
1573         /* Hint stack must not be empty. */
1574         if(HintStateStack == NIL)
1575                 elog(ERROR, "hint stack is empty");
1576
1577         /*
1578          * Take a hint at the head from the list, and free it.  Switch current_hint
1579          * to point new head (NULL if the list is empty).
1580          */
1581         HintStateStack = list_delete_first(HintStateStack);
1582         HintStateDelete(current_hint);
1583         if(HintStateStack == NIL)
1584                 current_hint = NULL;
1585         else
1586                 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1587 }
1588
1589 static PlannedStmt *
1590 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1591 {
1592         int                             save_nestlevel;
1593         PlannedStmt        *result;
1594         HintState          *hstate;
1595
1596         /*
1597          * Use standard planner if pg_hint_plan is disabled.  Other hook functions
1598          * try to change plan with current_hint if any, so set it to NULL.
1599          */
1600         if (!pg_hint_plan_enable_hint)
1601         {
1602                 current_hint = NULL;
1603
1604                 if (prev_planner)
1605                         return (*prev_planner) (parse, cursorOptions, boundParams);
1606                 else
1607                         return standard_planner(parse, cursorOptions, boundParams);
1608         }
1609
1610         /* Create hint struct from parse tree. */
1611         hstate = parse_head_comment(parse);
1612
1613         /*
1614          * Use standard planner if the statement has not valid hint.  Other hook
1615          * functions try to change plan with current_hint if any, so set it to
1616          * NULL.
1617          */
1618         if (!hstate)
1619         {
1620                 current_hint = NULL;
1621
1622                 if (prev_planner)
1623                         return (*prev_planner) (parse, cursorOptions, boundParams);
1624                 else
1625                         return standard_planner(parse, cursorOptions, boundParams);
1626         }
1627
1628         /*
1629          * Push new hint struct to the hint stack to disable previous hint context.
1630          */
1631         push_hint(hstate);
1632
1633         /* Set GUC parameters which are specified with Set hint. */
1634         save_nestlevel = set_config_options(current_hint->set_hints,
1635                                                                                 current_hint->num_hints[HINT_TYPE_SET],
1636                                                                                 current_hint->context);
1637
1638         if (enable_seqscan)
1639                 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1640         if (enable_indexscan)
1641                 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1642         if (enable_bitmapscan)
1643                 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1644         if (enable_tidscan)
1645                 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1646 #if PG_VERSION_NUM >= 90200
1647         if (enable_indexonlyscan)
1648                 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1649 #endif
1650         if (enable_nestloop)
1651                 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1652         if (enable_mergejoin)
1653                 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1654         if (enable_hashjoin)
1655                 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1656
1657         /*
1658          * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1659          * state when this planner started when error occurred in planner.
1660          */
1661         PG_TRY();
1662         {
1663                 if (prev_planner)
1664                         result = (*prev_planner) (parse, cursorOptions, boundParams);
1665                 else
1666                         result = standard_planner(parse, cursorOptions, boundParams);
1667         }
1668         PG_CATCH();
1669         {
1670                 /*
1671                  * Rollback changes of GUC parameters, and pop current hint context
1672                  * from hint stack to rewind the state.
1673                  */
1674                 AtEOXact_GUC(true, save_nestlevel);
1675                 pop_hint();
1676                 PG_RE_THROW();
1677         }
1678         PG_END_TRY();
1679
1680         /* Print hint in debug mode. */
1681         if (pg_hint_plan_debug_print)
1682                 HintStateDump(current_hint);
1683
1684         /*
1685          * Rollback changes of GUC parameters, and pop current hint context from
1686          * hint stack to rewind the state.
1687          */
1688         AtEOXact_GUC(true, save_nestlevel);
1689         pop_hint();
1690
1691         return result;
1692 }
1693
1694 /*
1695  * Return scan method hint which matches given aliasname.
1696  */
1697 static ScanMethodHint *
1698 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1699 {
1700         RangeTblEntry  *rte;
1701         int                             i;
1702
1703         /*
1704          * We can't apply scan method hint if the relation is:
1705          *   - not a base relation
1706          *   - not an ordinary relation (such as join and subquery)
1707          */
1708         if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1709                 return NULL;
1710
1711         rte = root->simple_rte_array[rel->relid];
1712
1713         /* We can't force scan method of foreign tables */
1714         if (rte->relkind == RELKIND_FOREIGN_TABLE)
1715                 return NULL;
1716
1717         /* Find scan method hint, which matches given names, from the list. */
1718         for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1719         {
1720                 ScanMethodHint *hint = current_hint->scan_hints[i];
1721
1722                 /* We ignore disabled hints. */
1723                 if (!hint_state_enabled(hint))
1724                         continue;
1725
1726                 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1727                         return hint;
1728         }
1729
1730         return NULL;
1731 }
1732
1733 static void
1734 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1735 {
1736         ListCell           *cell;
1737         ListCell           *prev;
1738         ListCell           *next;
1739
1740         /*
1741          * We delete all the IndexOptInfo list and prevent you from being usable by
1742          * a scan.
1743          */
1744         if (hint->enforce_mask == ENABLE_SEQSCAN ||
1745                 hint->enforce_mask == ENABLE_TIDSCAN)
1746         {
1747                 list_free_deep(rel->indexlist);
1748                 rel->indexlist = NIL;
1749                 hint->base.state = HINT_STATE_USED;
1750
1751                 return;
1752         }
1753
1754         /*
1755          * When a list of indexes is not specified, we just use all indexes.
1756          */
1757         if (hint->indexnames == NIL)
1758                 return;
1759
1760         /*
1761          * Leaving only an specified index, we delete it from a IndexOptInfo list
1762          * other than it.
1763          */
1764         prev = NULL;
1765         for (cell = list_head(rel->indexlist); cell; cell = next)
1766         {
1767                 IndexOptInfo   *info = (IndexOptInfo *) lfirst(cell);
1768                 char               *indexname = get_rel_name(info->indexoid);
1769                 ListCell           *l;
1770                 bool                    use_index = false;
1771
1772                 next = lnext(cell);
1773
1774                 foreach(l, hint->indexnames)
1775                 {
1776                         if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1777                         {
1778                                 use_index = true;
1779                                 break;
1780                         }
1781                 }
1782
1783                 if (!use_index)
1784                         rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1785                 else
1786                         prev = cell;
1787
1788                 pfree(indexname);
1789         }
1790 }
1791
1792 static void
1793 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1794                                                            bool inhparent, RelOptInfo *rel)
1795 {
1796         ScanMethodHint *hint;
1797
1798         if (prev_get_relation_info)
1799                 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1800
1801         /* Do nothing if we don't have valid hint in this context. */
1802         if (!current_hint)
1803                 return;
1804
1805         if (inhparent)
1806         {
1807                 /* store does relids of parent table. */
1808                 current_hint->parent_relid = rel->relid;
1809         }
1810         else if (current_hint->parent_relid != 0)
1811         {
1812                 /*
1813                  * We use the same GUC parameter if this table is the child table of a
1814                  * table called pg_hint_plan_get_relation_info just before that.
1815                  */
1816                 ListCell   *l;
1817
1818                 /* append_rel_list contains all append rels; ignore others */
1819                 foreach(l, root->append_rel_list)
1820                 {
1821                         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1822
1823                         /* This rel is child table. */
1824                         if (appinfo->parent_relid == current_hint->parent_relid &&
1825                                 appinfo->child_relid == rel->relid)
1826                         {
1827                                 if (current_hint->parent_hint)
1828                                         delete_indexes(current_hint->parent_hint, rel);
1829
1830                                 return;
1831                         }
1832                 }
1833
1834                 /* This rel is not inherit table. */
1835                 current_hint->parent_relid = 0;
1836                 current_hint->parent_hint = NULL;
1837         }
1838
1839         /*
1840          * If scan method hint was given, reset GUC parameters which control
1841          * planner behavior about choosing scan methods.
1842          */
1843         if ((hint = find_scan_hint(root, rel)) == NULL)
1844         {
1845                 set_scan_config_options(current_hint->init_scan_mask,
1846                                                                 current_hint->context);
1847                 return;
1848         }
1849         set_scan_config_options(hint->enforce_mask, current_hint->context);
1850         hint->base.state = HINT_STATE_USED;
1851         if (inhparent)
1852                 current_hint->parent_hint = hint;
1853
1854         delete_indexes(hint, rel);
1855 }
1856
1857 /*
1858  * Return index of relation which matches given aliasname, or 0 if not found.
1859  * If same aliasname was used multiple times in a query, return -1.
1860  */
1861 static int
1862 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1863                                          const char *str)
1864 {
1865         int             i;
1866         Index   found = 0;
1867
1868         for (i = 1; i < root->simple_rel_array_size; i++)
1869         {
1870                 ListCell   *l;
1871
1872                 if (root->simple_rel_array[i] == NULL)
1873                         continue;
1874
1875                 Assert(i == root->simple_rel_array[i]->relid);
1876
1877                 if (RelnameCmp(&aliasname,
1878                                            &root->simple_rte_array[i]->eref->aliasname) != 0)
1879                         continue;
1880
1881                 foreach(l, initial_rels)
1882                 {
1883                         RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1884
1885                         if (rel->reloptkind == RELOPT_BASEREL)
1886                         {
1887                                 if (rel->relid != i)
1888                                         continue;
1889                         }
1890                         else
1891                         {
1892                                 Assert(rel->reloptkind == RELOPT_JOINREL);
1893
1894                                 if (!bms_is_member(i, rel->relids))
1895                                         continue;
1896                         }
1897
1898                         if (found != 0)
1899                         {
1900                                 parse_ereport(str,
1901                                                           ("Relation name \"%s\" is ambiguous.",
1902                                                            aliasname));
1903                                 return -1;
1904                         }
1905
1906                         found = i;
1907                         break;
1908                 }
1909
1910         }
1911
1912         return found;
1913 }
1914
1915 /*
1916  * Return join hint which matches given joinrelids.
1917  */
1918 static JoinMethodHint *
1919 find_join_hint(Relids joinrelids)
1920 {
1921         List       *join_hint;
1922         ListCell   *l;
1923
1924         join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1925
1926         foreach(l, join_hint)
1927         {
1928                 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1929
1930                 if (bms_equal(joinrelids, hint->joinrelids))
1931                         return hint;
1932         }
1933
1934         return NULL;
1935 }
1936
1937 /*
1938  * Transform join method hint into handy form.
1939  * 
1940  *   - create bitmap of relids from alias names, to make it easier to check
1941  *     whether a join path matches a join method hint.
1942  *   - add join method hints which are necessary to enforce join order
1943  *     specified by Leading hint
1944  */
1945 static void
1946 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
1947                 List *initial_rels, JoinMethodHint **join_method_hints)
1948 {
1949         int                             i;
1950         int                             relid;
1951         LeadingHint        *lhint;
1952         Relids                  joinrelids;
1953         int                             njoinrels;
1954         ListCell           *l;
1955
1956         /*
1957          * Create bitmap of relids from alias names for each join method hint.
1958          * Bitmaps are more handy than strings in join searching.
1959          */
1960         for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1961         {
1962                 JoinMethodHint *hint = hstate->join_hints[i];
1963                 int     j;
1964
1965                 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1966                         continue;
1967
1968                 bms_free(hint->joinrelids);
1969                 hint->joinrelids = NULL;
1970                 relid = 0;
1971                 for (j = 0; j < hint->nrels; j++)
1972                 {
1973                         char   *relname = hint->relnames[j];
1974
1975                         relid = find_relid_aliasname(root, relname, initial_rels,
1976                                                                                  hint->base.hint_str);
1977
1978                         if (relid == -1)
1979                                 hint->base.state = HINT_STATE_ERROR;
1980
1981                         if (relid <= 0)
1982                                 break;
1983
1984                         if (bms_is_member(relid, hint->joinrelids))
1985                         {
1986                                 parse_ereport(hint->base.hint_str,
1987                                                           ("Relation name \"%s\" is duplicated.", relname));
1988                                 hint->base.state = HINT_STATE_ERROR;
1989                                 break;
1990                         }
1991
1992                         hint->joinrelids = bms_add_member(hint->joinrelids, relid);
1993                 }
1994
1995                 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
1996                         continue;
1997
1998                 hstate->join_hint_level[hint->nrels] =
1999                         lappend(hstate->join_hint_level[hint->nrels], hint);
2000         }
2001
2002         /* Do nothing if no Leading hint was supplied. */
2003         if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2004                 return;
2005
2006         /* Do nothing if Leading hint is invalid. */
2007         lhint = hstate->leading_hint;
2008         if (!hint_state_enabled(lhint))
2009                 return;
2010
2011         /*
2012          * We need join method hints which fit specified join order in every join
2013          * level.  For example, Leading(A B C) virtually requires following join
2014          * method hints, if no join method hint supplied:
2015          *   - level 1: none
2016          *   - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2017          *   - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2018          *
2019          * If we already have join method hint which fits specified join order in
2020          * that join level, we leave it as-is and don't add new hints.
2021          */
2022         joinrelids = NULL;
2023         njoinrels = 0;
2024         foreach(l, lhint->relations)
2025         {
2026                 char   *relname = (char *)lfirst(l);
2027                 JoinMethodHint *hint;
2028
2029                 /*
2030                  * Find relid of the relation which has given name.  If we have the
2031                  * name given in Leading hint multiple times in the join, nothing to
2032                  * do.
2033                  */
2034                 relid = find_relid_aliasname(root, relname, initial_rels,
2035                                                                          hstate->hint_str);
2036                 if (relid == -1)
2037                 {
2038                         bms_free(joinrelids);
2039                         return;
2040                 }
2041                 if (relid == 0)
2042                         continue;
2043
2044                 /* Found relid must not be in joinrelids. */
2045                 if (bms_is_member(relid, joinrelids))
2046                 {
2047                         parse_ereport(lhint->base.hint_str,
2048                                                   ("Relation name \"%s\" is duplicated.", relname));
2049                         lhint->base.state = HINT_STATE_ERROR;
2050                         bms_free(joinrelids);
2051                         return;
2052                 }
2053
2054                 /* Create bitmap of relids for current join level. */
2055                 joinrelids = bms_add_member(joinrelids, relid);
2056                 njoinrels++;
2057
2058                 /* We never have join method hint for single relation. */
2059                 if (njoinrels < 2)
2060                         continue;
2061
2062                 /*
2063                  * If we don't have join method hint, create new one for the
2064                  * join combination with all join methods are enabled.
2065                  */
2066                 hint = find_join_hint(joinrelids);
2067                 if (hint == NULL)
2068                 {
2069                         /*
2070                          * Here relnames is not set, since Relids bitmap is sufficient to
2071                          * control paths of this query afterward.
2072                          */
2073                         hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
2074                                                                                                                    HINT_LEADING);
2075                         hint->base.state = HINT_STATE_USED;
2076                         hint->nrels = njoinrels;
2077                         hint->enforce_mask = ENABLE_ALL_JOIN;
2078                         hint->joinrelids = bms_copy(joinrelids);
2079                 }
2080
2081                 join_method_hints[njoinrels] = hint;
2082
2083                 if (njoinrels >= nbaserel)
2084                         break;
2085         }
2086
2087         bms_free(joinrelids);
2088
2089         if (njoinrels < 2)
2090                 return;
2091
2092         /*
2093          * Delete all join hints which have different combination from Leading
2094          * hint.
2095          */
2096         for (i = 2; i <= njoinrels; i++)
2097         {
2098                 list_free(hstate->join_hint_level[i]);
2099
2100                 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2101         }
2102
2103         if (hint_state_enabled(lhint))
2104                 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2105
2106         lhint->base.state = HINT_STATE_USED;
2107
2108 }
2109
2110 /*
2111  * set_plain_rel_pathlist
2112  *        Build access paths for a plain relation (no subquery, no inheritance)
2113  *
2114  * This function was copied and edited from set_plain_rel_pathlist() in
2115  * src/backend/optimizer/path/allpaths.c
2116  */
2117 static void
2118 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2119 {
2120         /* Consider sequential scan */
2121 #if PG_VERSION_NUM >= 90200
2122         add_path(rel, create_seqscan_path(root, rel, NULL));
2123 #else
2124         add_path(rel, create_seqscan_path(root, rel));
2125 #endif
2126
2127         /* Consider index scans */
2128         create_index_paths(root, rel);
2129
2130         /* Consider TID scans */
2131         create_tidscan_paths(root, rel);
2132
2133         /* Now find the cheapest of the paths for this rel */
2134         set_cheapest(rel);
2135 }
2136
2137 static void
2138 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2139                                   List *initial_rels)
2140 {
2141         ListCell   *l;
2142
2143         foreach(l, initial_rels)
2144         {
2145                 RelOptInfo         *rel = (RelOptInfo *) lfirst(l);
2146                 RangeTblEntry  *rte;
2147                 ScanMethodHint *hint;
2148
2149                 /* Skip relations which we can't choose scan method. */
2150                 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2151                         continue;
2152
2153                 rte = root->simple_rte_array[rel->relid];
2154
2155                 /* We can't force scan method of foreign tables */
2156                 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2157                         continue;
2158
2159                 /*
2160                  * Create scan paths with GUC parameters which are at the beginning of
2161                  * planner if scan method hint is not specified, otherwise use
2162                  * specified hints and mark the hint as used.
2163                  */
2164                 if ((hint = find_scan_hint(root, rel)) == NULL)
2165                         set_scan_config_options(hstate->init_scan_mask,
2166                                                                         hstate->context);
2167                 else
2168                 {
2169                         set_scan_config_options(hint->enforce_mask, hstate->context);
2170                         hint->base.state = HINT_STATE_USED;
2171                 }
2172
2173                 list_free_deep(rel->pathlist);
2174                 rel->pathlist = NIL;
2175                 if (rte->inh)
2176                 {
2177                         /* It's an "append relation", process accordingly */
2178                         set_append_rel_pathlist(root, rel, rel->relid, rte);
2179                 }
2180                 else
2181                 {
2182                         set_plain_rel_pathlist(root, rel, rte);
2183                 }
2184         }
2185
2186         /*
2187          * Restore the GUC variables we set above.
2188          */
2189         set_scan_config_options(hstate->init_scan_mask, hstate->context);
2190 }
2191
2192 /*
2193  * wrapper of make_join_rel()
2194  *
2195  * call make_join_rel() after changing enable_* parameters according to given
2196  * hints.
2197  */
2198 static RelOptInfo *
2199 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2200 {
2201         Relids                  joinrelids;
2202         JoinMethodHint *hint;
2203         RelOptInfo         *rel;
2204         int                             save_nestlevel;
2205
2206         joinrelids = bms_union(rel1->relids, rel2->relids);
2207         hint = find_join_hint(joinrelids);
2208         bms_free(joinrelids);
2209
2210         if (!hint)
2211                 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2212
2213         save_nestlevel = NewGUCNestLevel();
2214
2215         set_join_config_options(hint->enforce_mask, current_hint->context);
2216
2217         rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2218         hint->base.state = HINT_STATE_USED;
2219
2220         /*
2221          * Restore the GUC variables we set above.
2222          */
2223         AtEOXact_GUC(true, save_nestlevel);
2224
2225         return rel;
2226 }
2227
2228 static int
2229 get_num_baserels(List *initial_rels)
2230 {
2231         int                     nbaserel = 0;
2232         ListCell   *l;
2233
2234         foreach(l, initial_rels)
2235         {
2236                 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2237
2238                 if (rel->reloptkind == RELOPT_BASEREL)
2239                         nbaserel++;
2240                 else if (rel->reloptkind ==RELOPT_JOINREL)
2241                         nbaserel+= bms_num_members(rel->relids);
2242                 else
2243                 {
2244                         /* other values not expected here */
2245                         elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
2246                 }
2247         }
2248
2249         return nbaserel;
2250 }
2251
2252 static RelOptInfo *
2253 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2254                                                  List *initial_rels)
2255 {
2256         JoinMethodHint **join_method_hints;
2257         int                     nbaserel;
2258         RelOptInfo *rel;
2259         int                     i;
2260
2261         /*
2262          * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2263          * valid hint is supplied.
2264          */
2265         if (!current_hint)
2266         {
2267                 if (prev_join_search)
2268                         return (*prev_join_search) (root, levels_needed, initial_rels);
2269                 else if (enable_geqo && levels_needed >= geqo_threshold)
2270                         return geqo(root, levels_needed, initial_rels);
2271                 else
2272                         return standard_join_search(root, levels_needed, initial_rels);
2273         }
2274
2275         /* We apply scan method hint rebuild scan path. */
2276         rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2277
2278         /*
2279          * In the case using GEQO, only scan method hints and Set hints have
2280          * effect.  Join method and join order is not controllable by hints.
2281          */
2282         if (enable_geqo && levels_needed >= geqo_threshold)
2283                 return geqo(root, levels_needed, initial_rels);
2284
2285         nbaserel = get_num_baserels(initial_rels);
2286         current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2287         join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2288
2289         transform_join_hints(current_hint, root, nbaserel, initial_rels,
2290                                                  join_method_hints);
2291
2292         rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2293
2294         for (i = 2; i <= nbaserel; i++)
2295         {
2296                 list_free(current_hint->join_hint_level[i]);
2297
2298                 /* free Leading hint only */
2299                 if (join_method_hints[i] != NULL &&
2300                         join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2301                         JoinMethodHintDelete(join_method_hints[i]);
2302         }
2303         pfree(current_hint->join_hint_level);
2304         pfree(join_method_hints);
2305
2306         if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2307                 hint_state_enabled(current_hint->leading_hint))
2308                 set_join_config_options(current_hint->init_join_mask,
2309                                                                 current_hint->context);
2310
2311         return rel;
2312 }
2313
2314 /*
2315  * set_rel_pathlist
2316  *        Build access paths for a base relation
2317  *
2318  * This function was copied and edited from set_rel_pathlist() in
2319  * src/backend/optimizer/path/allpaths.c
2320  */
2321 static void
2322 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2323                                  Index rti, RangeTblEntry *rte)
2324 {
2325 #if PG_VERSION_NUM >= 90200
2326         if (IS_DUMMY_REL(rel))
2327         {
2328                 /* We already proved the relation empty, so nothing more to do */
2329         }
2330         else if (rte->inh)
2331 #else
2332         if (rte->inh)
2333 #endif
2334         {
2335                 /* It's an "append relation", process accordingly */
2336                 set_append_rel_pathlist(root, rel, rti, rte);
2337         }
2338         else
2339         {
2340                 if (rel->rtekind == RTE_RELATION)
2341                 {
2342                         if (rte->relkind == RELKIND_RELATION)
2343                         {
2344                                 /* Plain relation */
2345                                 set_plain_rel_pathlist(root, rel, rte);
2346                         }
2347                         else
2348                                 elog(ERROR, "unexpected relkind: %c", rte->relkind);
2349                 }
2350                 else
2351                         elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
2352         }
2353 }
2354
2355 #define standard_join_search pg_hint_plan_standard_join_search
2356 #define join_search_one_level pg_hint_plan_join_search_one_level
2357 #define make_join_rel make_join_rel_wrapper
2358 #include "core.c"
2359
2360 #undef make_join_rel
2361 #define make_join_rel pg_hint_plan_make_join_rel
2362 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2363 do { \
2364         ScanMethodHint *hint = NULL; \
2365         if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2366         { \
2367                 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2368                 hint->base.state = HINT_STATE_USED; \
2369         } \
2370         add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2371         if (hint != NULL) \
2372                 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2373 } while(0)
2374 #include "make_join_rel.c"