OSDN Git Service

使用例セクションを追加しヒントグループごとにSQL文を記述
[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, char *value_type, 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 %s.", value_type));
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                 char   *type;
950
951                 type = pstrdup(value_type);
952                 type[0] = toupper(type[0]);
953                 parse_ereport(str, ("%s is necessary.", type));
954
955                 pfree(buf.data);
956                 pfree(type);
957
958                 return NULL;
959         }
960
961         /* Truncate name if it's too long */
962         if (truncate)
963                 truncate_identifier(buf.data, strlen(buf.data), true);
964
965         *word = buf.data;
966
967         return str;
968 }
969
970 static void
971 parse_hints(HintState *hstate, Query *parse, const char *str)
972 {
973         StringInfoData  buf;
974         char               *head;
975
976         initStringInfo(&buf);
977         while (*str != '\0')
978         {
979                 const HintParser *parser;
980
981                 /* in error message, we output the comment including the keyword. */
982                 head = (char *) str;
983
984                 /* parse only the keyword of the hint. */
985                 resetStringInfo(&buf);
986                 str = parse_keyword(str, &buf);
987
988                 for (parser = parsers; parser->keyword != NULL; parser++)
989                 {
990                         char   *keyword = parser->keyword;
991                         Hint   *hint;
992
993                         if (strcasecmp(buf.data, keyword) != 0)
994                                 continue;
995
996                         hint = parser->create_func(head, keyword);
997
998                         /* parser of each hint does parse in a parenthesis. */
999                         if ((str = skip_opened_parenthesis(str)) == NULL ||
1000                                 (str = hint->parser_func(hint, hstate, parse, str)) == NULL ||
1001                                 (str = skip_closed_parenthesis(str)) == NULL)
1002                         {
1003                                 hint->delete_func(hint);
1004                                 pfree(buf.data);
1005                                 return;
1006                         }
1007
1008                         /*
1009                          * Add hint information into all_hints array.  If we don't have
1010                          * enough space, double the array.
1011                          */
1012                         if (hstate->nall_hints == 0)
1013                         {
1014                                 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1015                                 hstate->all_hints = (Hint **)
1016                                         palloc(sizeof(Hint *) * hstate->max_all_hints);
1017                         }
1018                         else if (hstate->nall_hints == hstate->max_all_hints)
1019                         {
1020                                 hstate->max_all_hints *= 2;
1021                                 hstate->all_hints = (Hint **)
1022                                         repalloc(hstate->all_hints,
1023                                                          sizeof(Hint *) * hstate->max_all_hints);
1024                         }
1025
1026                         hstate->all_hints[hstate->nall_hints] = hint;
1027                         hstate->nall_hints++;
1028
1029                         skip_space(str);
1030
1031                         break;
1032                 }
1033
1034                 if (parser->keyword == NULL)
1035                 {
1036                         parse_ereport(head,
1037                                                   ("Unrecognized hint keyword \"%s\".", buf.data));
1038                         pfree(buf.data);
1039                         return;
1040                 }
1041         }
1042
1043         pfree(buf.data);
1044 }
1045
1046 /*
1047  * Do basic parsing of the query head comment.
1048  */
1049 static HintState *
1050 parse_head_comment(Query *parse)
1051 {
1052         const char *p;
1053         char       *head;
1054         char       *tail;
1055         int                     len;
1056         int                     i;
1057         HintState   *hstate;
1058
1059         /* get client-supplied query string. */
1060         if (stmt_name)
1061         {
1062                 PreparedStatement  *entry;
1063
1064                 entry = FetchPreparedStatement(stmt_name, true);
1065                 p = entry->plansource->query_string;
1066         }
1067         else
1068                 p = debug_query_string;
1069
1070         if (p == NULL)
1071                 return NULL;
1072
1073         /* extract query head comment. */
1074         len = strlen(HINT_START);
1075         skip_space(p);
1076         if (strncmp(p, HINT_START, len))
1077                 return NULL;
1078
1079         head = (char *) p;
1080         p += len;
1081         skip_space(p);
1082
1083         /* find hint end keyword. */
1084         if ((tail = strstr(p, HINT_END)) == NULL)
1085         {
1086                 parse_ereport(head, ("Unterminated block comment."));
1087                 return NULL;
1088         }
1089
1090         /* We don't support nested block comments. */
1091         if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1092         {
1093                 parse_ereport(head, ("Nested block comments are not supported."));
1094                 return NULL;
1095         }
1096
1097         /* Make a copy of hint. */
1098         len = tail - p;
1099         head = palloc(len + 1);
1100         memcpy(head, p, len);
1101         head[len] = '\0';
1102         p = head;
1103
1104         hstate = HintStateCreate();
1105         hstate->hint_str = head;
1106
1107         /* parse each hint. */
1108         parse_hints(hstate, parse, p);
1109
1110         /* When nothing specified a hint, we free HintState and returns NULL. */
1111         if (hstate->nall_hints == 0)
1112         {
1113                 HintStateDelete(hstate);
1114                 return NULL;
1115         }
1116
1117         /* Sort hints in order of original position. */
1118         qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1119                   HintCmpWithPos);
1120
1121         /*
1122          * If we have hints which are specified for an object, mark preceding one
1123          * as 'duplicated' to ignore it in planner phase.
1124          */
1125         for (i = 0; i < hstate->nall_hints; i++)
1126         {
1127                 Hint   *cur_hint = hstate->all_hints[i];
1128                 Hint   *next_hint;
1129
1130                 /* Count up hints per hint-type. */
1131                 hstate->num_hints[cur_hint->type]++;
1132
1133                 /* If we don't have next, nothing to compare. */
1134                 if (i + 1 >= hstate->nall_hints)
1135                         break;
1136                 next_hint = hstate->all_hints[i + 1];
1137
1138                 /*
1139                  * We need to pass address of hint pointers, because HintCmp has
1140                  * been designed to be used with qsort.
1141                  */
1142                 if (HintCmp(&cur_hint, &next_hint) == 0)
1143                 {
1144                         parse_ereport(cur_hint->hint_str,
1145                                                   ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1146                         cur_hint->state = HINT_STATE_DUPLICATION;
1147                 }
1148         }
1149
1150         /*
1151          * Make sure that per-type array pointers point proper position in the
1152          * array which consists of all hints.
1153          */
1154         hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1155         hstate->join_hints = (JoinMethodHint **) hstate->all_hints +
1156                 hstate->num_hints[HINT_TYPE_SCAN_METHOD];
1157         hstate->leading_hint = (LeadingHint *) hstate->all_hints[
1158                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1159                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1160                 hstate->num_hints[HINT_TYPE_LEADING] - 1];
1161         hstate->set_hints = (SetHint **) hstate->all_hints +
1162                 hstate->num_hints[HINT_TYPE_SCAN_METHOD] +
1163                 hstate->num_hints[HINT_TYPE_JOIN_METHOD] +
1164                 hstate->num_hints[HINT_TYPE_LEADING];
1165
1166         return hstate;
1167 }
1168
1169 /*
1170  * Parse inside of parentheses of scan-method hints.
1171  */
1172 static const char *
1173 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1174                                         const char *str)
1175 {
1176         const char *keyword = hint->base.keyword;
1177
1178         /* Given hint is invalid if relation name can't be parsed. */
1179         if ((str = parse_quote_value(str, &hint->relname, "relation name", true))
1180                 == NULL)
1181                 return NULL;
1182
1183         skip_space(str);
1184
1185         /* Parse index name(s) if given hint accepts. */
1186         if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
1187 #if PG_VERSION_NUM >= 90200
1188                 strcmp(keyword, HINT_INDEXONLYSCAN) == 0 ||
1189 #endif
1190                 strcmp(keyword, HINT_BITMAPSCAN) == 0)
1191         {
1192                 while (*str != ')' && *str != '\0')
1193                 {
1194                         char       *indexname;
1195
1196                         str = parse_quote_value(str, &indexname, "index name", true);
1197                         if (str == NULL)
1198                                 return NULL;
1199
1200                         hint->indexnames = lappend(hint->indexnames, indexname);
1201                         skip_space(str);
1202                 }
1203         }
1204
1205         /* Set a bit for specified hint. */
1206         if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
1207                 hint->enforce_mask = ENABLE_SEQSCAN;
1208         else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
1209                 hint->enforce_mask = ENABLE_INDEXSCAN;
1210         else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
1211                 hint->enforce_mask = ENABLE_BITMAPSCAN;
1212         else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
1213                 hint->enforce_mask = ENABLE_TIDSCAN;
1214         else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
1215                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1216         else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
1217                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1218         else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
1219                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1220         else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
1221                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1222 #if PG_VERSION_NUM >= 90200
1223         else if (strcasecmp(keyword, HINT_INDEXONLYSCAN) == 0)
1224                 hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1225         else if (strcasecmp(keyword, HINT_NOINDEXONLYSCAN) == 0)
1226                 hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1227 #endif
1228         else
1229         {
1230                 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1231                 return NULL;
1232         }
1233
1234         return str;
1235 }
1236
1237 static const char *
1238 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1239                                         const char *str)
1240 {
1241         char       *relname;
1242         const char *keyword = hint->base.keyword;
1243
1244         skip_space(str);
1245
1246         hint->relnames = palloc(sizeof(char *));
1247
1248         while ((str = parse_quote_value(str, &relname, "relation name", true))
1249                    != NULL)
1250         {
1251                 hint->nrels++;
1252                 hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
1253                 hint->relnames[hint->nrels - 1] = relname;
1254
1255                 skip_space(str);
1256                 if (*str == ')')
1257                         break;
1258         }
1259
1260         if (str == NULL)
1261                 return NULL;
1262
1263         /* A join hint requires at least two relations to be specified. */
1264         if (hint->nrels < 2)
1265         {
1266                 parse_ereport(str,
1267                                           ("%s hint requires at least two relations.",
1268                                            hint->base.keyword));
1269                 hint->base.state = HINT_STATE_ERROR;
1270         }
1271
1272         /* Sort hints in alphabetical order of relation names. */
1273         qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1274
1275         if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
1276                 hint->enforce_mask = ENABLE_NESTLOOP;
1277         else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
1278                 hint->enforce_mask = ENABLE_MERGEJOIN;
1279         else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
1280                 hint->enforce_mask = ENABLE_HASHJOIN;
1281         else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
1282                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1283         else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
1284                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1285         else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
1286                 hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1287         else
1288         {
1289                 parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1290                 return NULL;
1291         }
1292
1293         return str;
1294 }
1295
1296 static const char *
1297 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1298                                  const char *str)
1299 {
1300         skip_space(str);
1301
1302         while (*str != ')')
1303         {
1304                 char   *relname;
1305
1306                 if ((str = parse_quote_value(str, &relname, "relation name", true))
1307                         == NULL)
1308                         return NULL;
1309
1310                 hint->relations = lappend(hint->relations, relname);
1311
1312                 skip_space(str);
1313         }
1314
1315         /* A Leading hint requires at least two relations to be specified. */
1316         if (list_length(hint->relations) < 2)
1317         {
1318                 parse_ereport(hint->base.hint_str,
1319                                           ("%s hint requires at least two relations.",
1320                                            HINT_LEADING));
1321                 hint->base.state = HINT_STATE_ERROR;
1322         }
1323
1324         return str;
1325 }
1326
1327 static const char *
1328 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1329 {
1330         if ((str = parse_quote_value(str, &hint->name, "parameter name", true))
1331                 == NULL ||
1332                 (str = parse_quote_value(str, &hint->value, "parameter value", false))
1333                 == NULL)
1334                 return NULL;
1335
1336         return str;
1337 }
1338
1339 /*
1340  * set GUC parameter functions
1341  */
1342
1343 static int
1344 set_config_option_wrapper(const char *name, const char *value,
1345                                                   GucContext context, GucSource source,
1346                                                   GucAction action, bool changeVal, int elevel)
1347 {
1348         int                             result = 0;
1349         MemoryContext   ccxt = CurrentMemoryContext;
1350
1351         PG_TRY();
1352         {
1353 #if PG_VERSION_NUM >= 90200
1354                 result = set_config_option(name, value, context, source,
1355                                                                    action, changeVal, 0);
1356 #else
1357                 result = set_config_option(name, value, context, source,
1358                                                                    action, changeVal);
1359 #endif
1360         }
1361         PG_CATCH();
1362         {
1363                 ErrorData          *errdata;
1364
1365                 /* Save error info */
1366                 MemoryContextSwitchTo(ccxt);
1367                 errdata = CopyErrorData();
1368                 FlushErrorState();
1369
1370                 ereport(elevel, (errcode(errdata->sqlerrcode),
1371                                 errmsg("%s", errdata->message),
1372                                 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1373                                 errdata->hint ? errhint("%s", errdata->hint) : 0));
1374                 FreeErrorData(errdata);
1375         }
1376         PG_END_TRY();
1377
1378         return result;
1379 }
1380
1381 static int
1382 set_config_options(SetHint **options, int noptions, GucContext context)
1383 {
1384         int     i;
1385         int     save_nestlevel;
1386
1387         save_nestlevel = NewGUCNestLevel();
1388
1389         for (i = 0; i < noptions; i++)
1390         {
1391                 SetHint    *hint = options[i];
1392                 int                     result;
1393
1394                 if (!hint_state_enabled(hint))
1395                         continue;
1396
1397                 result = set_config_option_wrapper(hint->name, hint->value, context,
1398                                                                                    PGC_S_SESSION, GUC_ACTION_SAVE, true,
1399                                                                                    pg_hint_plan_parse_messages);
1400                 if (result != 0)
1401                         hint->base.state = HINT_STATE_USED;
1402                 else
1403                         hint->base.state = HINT_STATE_ERROR;
1404         }
1405
1406         return save_nestlevel;
1407 }
1408
1409 #define SET_CONFIG_OPTION(name, type_bits) \
1410         set_config_option_wrapper((name), \
1411                 (mask & (type_bits)) ? "true" : "false", \
1412                 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1413
1414 static void
1415 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1416 {
1417         unsigned char   mask;
1418
1419         if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1420                 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1421 #if PG_VERSION_NUM >= 90200
1422                 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1423 #endif
1424                 )
1425                 mask = enforce_mask;
1426         else
1427                 mask = enforce_mask & current_hint->init_scan_mask;
1428
1429         SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1430         SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1431         SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1432         SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1433 #if PG_VERSION_NUM >= 90200
1434         SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1435 #endif
1436 }
1437
1438 static void
1439 set_join_config_options(unsigned char enforce_mask, GucContext context)
1440 {
1441         unsigned char   mask;
1442
1443         if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1444                 enforce_mask == ENABLE_HASHJOIN)
1445                 mask = enforce_mask;
1446         else
1447                 mask = enforce_mask & current_hint->init_join_mask;
1448
1449         SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1450         SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1451         SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1452 }
1453
1454 /*
1455  * pg_hint_plan hook functions
1456  */
1457
1458 static void
1459 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1460                                                         ParamListInfo params, bool isTopLevel,
1461                                                         DestReceiver *dest, char *completionTag)
1462 {
1463         Node                               *node;
1464
1465         if (!pg_hint_plan_enable_hint)
1466         {
1467                 if (prev_ProcessUtility)
1468                         (*prev_ProcessUtility) (parsetree, queryString, params,
1469                                                                         isTopLevel, dest, completionTag);
1470                 else
1471                         standard_ProcessUtility(parsetree, queryString, params,
1472                                                                         isTopLevel, dest, completionTag);
1473
1474                 return;
1475         }
1476
1477         node = parsetree;
1478         if (IsA(node, ExplainStmt))
1479         {
1480                 /*
1481                  * Draw out parse tree of actual query from Query struct of EXPLAIN
1482                  * statement.
1483                  */
1484                 ExplainStmt        *stmt;
1485                 Query              *query;
1486
1487                 stmt = (ExplainStmt *) node;
1488
1489                 Assert(IsA(stmt->query, Query));
1490                 query = (Query *) stmt->query;
1491
1492                 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
1493                         node = query->utilityStmt;
1494         }
1495
1496         /*
1497          * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
1498          * specified to preceding PREPARE command to use it as source of hints.
1499          */
1500         if (IsA(node, ExecuteStmt))
1501         {
1502                 ExecuteStmt        *stmt;
1503
1504                 stmt = (ExecuteStmt *) node;
1505                 stmt_name = stmt->name;
1506         }
1507 #if PG_VERSION_NUM >= 90200
1508         /*
1509          * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
1510          * specially here.
1511          */
1512         if (IsA(node, CreateTableAsStmt))
1513         {
1514                 CreateTableAsStmt          *stmt;
1515                 Query              *query;
1516
1517                 stmt = (CreateTableAsStmt *) node;
1518                 Assert(IsA(stmt->query, Query));
1519                 query = (Query *) stmt->query;
1520
1521                 if (query->commandType == CMD_UTILITY &&
1522                         IsA(query->utilityStmt, ExecuteStmt))
1523                 {
1524                         ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
1525                         stmt_name = estmt->name;
1526                 }
1527         }
1528 #endif
1529         if (stmt_name)
1530         {
1531                 PG_TRY();
1532                 {
1533                         if (prev_ProcessUtility)
1534                                 (*prev_ProcessUtility) (parsetree, queryString, params,
1535                                                                                 isTopLevel, dest, completionTag);
1536                         else
1537                                 standard_ProcessUtility(parsetree, queryString, params,
1538                                                                                 isTopLevel, dest, completionTag);
1539                 }
1540                 PG_CATCH();
1541                 {
1542                         stmt_name = NULL;
1543                         PG_RE_THROW();
1544                 }
1545                 PG_END_TRY();
1546
1547                 stmt_name = NULL;
1548
1549                 return;
1550         }
1551
1552         if (prev_ProcessUtility)
1553                 (*prev_ProcessUtility) (parsetree, queryString, params,
1554                                                                 isTopLevel, dest, completionTag);
1555         else
1556                 standard_ProcessUtility(parsetree, queryString, params,
1557                                                                 isTopLevel, dest, completionTag);
1558 }
1559
1560 /*
1561  * Push a hint into hint stack which is implemented with List struct.  Head of
1562  * list is top of stack.
1563  */
1564 static void
1565 push_hint(HintState *hstate)
1566 {
1567         /* Prepend new hint to the list means pushing to stack. */
1568         HintStateStack = lcons(hstate, HintStateStack);
1569
1570         /* Pushed hint is the one which should be used hereafter. */
1571         current_hint = hstate;
1572 }
1573
1574 /* Pop a hint from hint stack.  Popped hint is automatically discarded. */
1575 static void
1576 pop_hint(void)
1577 {
1578         /* Hint stack must not be empty. */
1579         if(HintStateStack == NIL)
1580                 elog(ERROR, "hint stack is empty");
1581
1582         /*
1583          * Take a hint at the head from the list, and free it.  Switch current_hint
1584          * to point new head (NULL if the list is empty).
1585          */
1586         HintStateStack = list_delete_first(HintStateStack);
1587         HintStateDelete(current_hint);
1588         if(HintStateStack == NIL)
1589                 current_hint = NULL;
1590         else
1591                 current_hint = (HintState *) lfirst(list_head(HintStateStack));
1592 }
1593
1594 static PlannedStmt *
1595 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
1596 {
1597         int                             save_nestlevel;
1598         PlannedStmt        *result;
1599         HintState          *hstate;
1600
1601         /*
1602          * Use standard planner if pg_hint_plan is disabled.  Other hook functions
1603          * try to change plan with current_hint if any, so set it to NULL.
1604          */
1605         if (!pg_hint_plan_enable_hint)
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         /* Create hint struct from parse tree. */
1616         hstate = parse_head_comment(parse);
1617
1618         /*
1619          * Use standard planner if the statement has not valid hint.  Other hook
1620          * functions try to change plan with current_hint if any, so set it to
1621          * NULL.
1622          */
1623         if (!hstate)
1624         {
1625                 current_hint = NULL;
1626
1627                 if (prev_planner)
1628                         return (*prev_planner) (parse, cursorOptions, boundParams);
1629                 else
1630                         return standard_planner(parse, cursorOptions, boundParams);
1631         }
1632
1633         /*
1634          * Push new hint struct to the hint stack to disable previous hint context.
1635          */
1636         push_hint(hstate);
1637
1638         /* Set GUC parameters which are specified with Set hint. */
1639         save_nestlevel = set_config_options(current_hint->set_hints,
1640                                                                                 current_hint->num_hints[HINT_TYPE_SET],
1641                                                                                 current_hint->context);
1642
1643         if (enable_seqscan)
1644                 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
1645         if (enable_indexscan)
1646                 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
1647         if (enable_bitmapscan)
1648                 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
1649         if (enable_tidscan)
1650                 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
1651 #if PG_VERSION_NUM >= 90200
1652         if (enable_indexonlyscan)
1653                 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
1654 #endif
1655         if (enable_nestloop)
1656                 current_hint->init_join_mask |= ENABLE_NESTLOOP;
1657         if (enable_mergejoin)
1658                 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
1659         if (enable_hashjoin)
1660                 current_hint->init_join_mask |= ENABLE_HASHJOIN;
1661
1662         /*
1663          * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
1664          * state when this planner started when error occurred in planner.
1665          */
1666         PG_TRY();
1667         {
1668                 if (prev_planner)
1669                         result = (*prev_planner) (parse, cursorOptions, boundParams);
1670                 else
1671                         result = standard_planner(parse, cursorOptions, boundParams);
1672         }
1673         PG_CATCH();
1674         {
1675                 /*
1676                  * Rollback changes of GUC parameters, and pop current hint context
1677                  * from hint stack to rewind the state.
1678                  */
1679                 AtEOXact_GUC(true, save_nestlevel);
1680                 pop_hint();
1681                 PG_RE_THROW();
1682         }
1683         PG_END_TRY();
1684
1685         /* Print hint in debug mode. */
1686         if (pg_hint_plan_debug_print)
1687                 HintStateDump(current_hint);
1688
1689         /*
1690          * Rollback changes of GUC parameters, and pop current hint context from
1691          * hint stack to rewind the state.
1692          */
1693         AtEOXact_GUC(true, save_nestlevel);
1694         pop_hint();
1695
1696         return result;
1697 }
1698
1699 /*
1700  * Return scan method hint which matches given aliasname.
1701  */
1702 static ScanMethodHint *
1703 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
1704 {
1705         RangeTblEntry  *rte;
1706         int                             i;
1707
1708         /*
1709          * We can't apply scan method hint if the relation is:
1710          *   - not a base relation
1711          *   - not an ordinary relation (such as join and subquery)
1712          */
1713         if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
1714                 return NULL;
1715
1716         rte = root->simple_rte_array[rel->relid];
1717
1718         /* We can't force scan method of foreign tables */
1719         if (rte->relkind == RELKIND_FOREIGN_TABLE)
1720                 return NULL;
1721
1722         /* Find scan method hint, which matches given names, from the list. */
1723         for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
1724         {
1725                 ScanMethodHint *hint = current_hint->scan_hints[i];
1726
1727                 /* We ignore disabled hints. */
1728                 if (!hint_state_enabled(hint))
1729                         continue;
1730
1731                 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
1732                         return hint;
1733         }
1734
1735         return NULL;
1736 }
1737
1738 static void
1739 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
1740 {
1741         ListCell           *cell;
1742         ListCell           *prev;
1743         ListCell           *next;
1744
1745         /*
1746          * We delete all the IndexOptInfo list and prevent you from being usable by
1747          * a scan.
1748          */
1749         if (hint->enforce_mask == ENABLE_SEQSCAN ||
1750                 hint->enforce_mask == ENABLE_TIDSCAN)
1751         {
1752                 list_free_deep(rel->indexlist);
1753                 rel->indexlist = NIL;
1754                 hint->base.state = HINT_STATE_USED;
1755
1756                 return;
1757         }
1758
1759         /*
1760          * When a list of indexes is not specified, we just use all indexes.
1761          */
1762         if (hint->indexnames == NIL)
1763                 return;
1764
1765         /*
1766          * Leaving only an specified index, we delete it from a IndexOptInfo list
1767          * other than it.
1768          */
1769         prev = NULL;
1770         for (cell = list_head(rel->indexlist); cell; cell = next)
1771         {
1772                 IndexOptInfo   *info = (IndexOptInfo *) lfirst(cell);
1773                 char               *indexname = get_rel_name(info->indexoid);
1774                 ListCell           *l;
1775                 bool                    use_index = false;
1776
1777                 next = lnext(cell);
1778
1779                 foreach(l, hint->indexnames)
1780                 {
1781                         if (RelnameCmp(&indexname, &lfirst(l)) == 0)
1782                         {
1783                                 use_index = true;
1784                                 break;
1785                         }
1786                 }
1787
1788                 if (!use_index)
1789                         rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
1790                 else
1791                         prev = cell;
1792
1793                 pfree(indexname);
1794         }
1795 }
1796
1797 static void
1798 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
1799                                                            bool inhparent, RelOptInfo *rel)
1800 {
1801         ScanMethodHint *hint;
1802
1803         if (prev_get_relation_info)
1804                 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
1805
1806         /* Do nothing if we don't have valid hint in this context. */
1807         if (!current_hint)
1808                 return;
1809
1810         if (inhparent)
1811         {
1812                 /* store does relids of parent table. */
1813                 current_hint->parent_relid = rel->relid;
1814         }
1815         else if (current_hint->parent_relid != 0)
1816         {
1817                 /*
1818                  * We use the same GUC parameter if this table is the child table of a
1819                  * table called pg_hint_plan_get_relation_info just before that.
1820                  */
1821                 ListCell   *l;
1822
1823                 /* append_rel_list contains all append rels; ignore others */
1824                 foreach(l, root->append_rel_list)
1825                 {
1826                         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1827
1828                         /* This rel is child table. */
1829                         if (appinfo->parent_relid == current_hint->parent_relid &&
1830                                 appinfo->child_relid == rel->relid)
1831                         {
1832                                 if (current_hint->parent_hint)
1833                                         delete_indexes(current_hint->parent_hint, rel);
1834
1835                                 return;
1836                         }
1837                 }
1838
1839                 /* This rel is not inherit table. */
1840                 current_hint->parent_relid = 0;
1841                 current_hint->parent_hint = NULL;
1842         }
1843
1844         /*
1845          * If scan method hint was given, reset GUC parameters which control
1846          * planner behavior about choosing scan methods.
1847          */
1848         if ((hint = find_scan_hint(root, rel)) == NULL)
1849         {
1850                 set_scan_config_options(current_hint->init_scan_mask,
1851                                                                 current_hint->context);
1852                 return;
1853         }
1854         set_scan_config_options(hint->enforce_mask, current_hint->context);
1855         hint->base.state = HINT_STATE_USED;
1856         if (inhparent)
1857                 current_hint->parent_hint = hint;
1858
1859         delete_indexes(hint, rel);
1860 }
1861
1862 /*
1863  * Return index of relation which matches given aliasname, or 0 if not found.
1864  * If same aliasname was used multiple times in a query, return -1.
1865  */
1866 static int
1867 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
1868                                          const char *str)
1869 {
1870         int             i;
1871         Index   found = 0;
1872
1873         for (i = 1; i < root->simple_rel_array_size; i++)
1874         {
1875                 ListCell   *l;
1876
1877                 if (root->simple_rel_array[i] == NULL)
1878                         continue;
1879
1880                 Assert(i == root->simple_rel_array[i]->relid);
1881
1882                 if (RelnameCmp(&aliasname,
1883                                            &root->simple_rte_array[i]->eref->aliasname) != 0)
1884                         continue;
1885
1886                 foreach(l, initial_rels)
1887                 {
1888                         RelOptInfo *rel = (RelOptInfo *) lfirst(l);
1889
1890                         if (rel->reloptkind == RELOPT_BASEREL)
1891                         {
1892                                 if (rel->relid != i)
1893                                         continue;
1894                         }
1895                         else
1896                         {
1897                                 Assert(rel->reloptkind == RELOPT_JOINREL);
1898
1899                                 if (!bms_is_member(i, rel->relids))
1900                                         continue;
1901                         }
1902
1903                         if (found != 0)
1904                         {
1905                                 parse_ereport(str,
1906                                                           ("Relation name \"%s\" is ambiguous.",
1907                                                            aliasname));
1908                                 return -1;
1909                         }
1910
1911                         found = i;
1912                         break;
1913                 }
1914
1915         }
1916
1917         return found;
1918 }
1919
1920 /*
1921  * Return join hint which matches given joinrelids.
1922  */
1923 static JoinMethodHint *
1924 find_join_hint(Relids joinrelids)
1925 {
1926         List       *join_hint;
1927         ListCell   *l;
1928
1929         join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
1930
1931         foreach(l, join_hint)
1932         {
1933                 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
1934
1935                 if (bms_equal(joinrelids, hint->joinrelids))
1936                         return hint;
1937         }
1938
1939         return NULL;
1940 }
1941
1942 /*
1943  * Transform join method hint into handy form.
1944  * 
1945  *   - create bitmap of relids from alias names, to make it easier to check
1946  *     whether a join path matches a join method hint.
1947  *   - add join method hints which are necessary to enforce join order
1948  *     specified by Leading hint
1949  */
1950 static void
1951 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
1952                 List *initial_rels, JoinMethodHint **join_method_hints)
1953 {
1954         int                             i;
1955         int                             relid;
1956         LeadingHint        *lhint;
1957         Relids                  joinrelids;
1958         int                             njoinrels;
1959         ListCell           *l;
1960
1961         /*
1962          * Create bitmap of relids from alias names for each join method hint.
1963          * Bitmaps are more handy than strings in join searching.
1964          */
1965         for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
1966         {
1967                 JoinMethodHint *hint = hstate->join_hints[i];
1968                 int     j;
1969
1970                 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
1971                         continue;
1972
1973                 bms_free(hint->joinrelids);
1974                 hint->joinrelids = NULL;
1975                 relid = 0;
1976                 for (j = 0; j < hint->nrels; j++)
1977                 {
1978                         char   *relname = hint->relnames[j];
1979
1980                         relid = find_relid_aliasname(root, relname, initial_rels,
1981                                                                                  hint->base.hint_str);
1982
1983                         if (relid == -1)
1984                                 hint->base.state = HINT_STATE_ERROR;
1985
1986                         if (relid <= 0)
1987                                 break;
1988
1989                         if (bms_is_member(relid, hint->joinrelids))
1990                         {
1991                                 parse_ereport(hint->base.hint_str,
1992                                                           ("Relation name \"%s\" is duplicated.", relname));
1993                                 hint->base.state = HINT_STATE_ERROR;
1994                                 break;
1995                         }
1996
1997                         hint->joinrelids = bms_add_member(hint->joinrelids, relid);
1998                 }
1999
2000                 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2001                         continue;
2002
2003                 hstate->join_hint_level[hint->nrels] =
2004                         lappend(hstate->join_hint_level[hint->nrels], hint);
2005         }
2006
2007         /* Do nothing if no Leading hint was supplied. */
2008         if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2009                 return;
2010
2011         /* Do nothing if Leading hint is invalid. */
2012         lhint = hstate->leading_hint;
2013         if (!hint_state_enabled(lhint))
2014                 return;
2015
2016         /*
2017          * We need join method hints which fit specified join order in every join
2018          * level.  For example, Leading(A B C) virtually requires following join
2019          * method hints, if no join method hint supplied:
2020          *   - level 1: none
2021          *   - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
2022          *   - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
2023          *
2024          * If we already have join method hint which fits specified join order in
2025          * that join level, we leave it as-is and don't add new hints.
2026          */
2027         joinrelids = NULL;
2028         njoinrels = 0;
2029         foreach(l, lhint->relations)
2030         {
2031                 char   *relname = (char *)lfirst(l);
2032                 JoinMethodHint *hint;
2033
2034                 /*
2035                  * Find relid of the relation which has given name.  If we have the
2036                  * name given in Leading hint multiple times in the join, nothing to
2037                  * do.
2038                  */
2039                 relid = find_relid_aliasname(root, relname, initial_rels,
2040                                                                          hstate->hint_str);
2041                 if (relid == -1)
2042                 {
2043                         bms_free(joinrelids);
2044                         return;
2045                 }
2046                 if (relid == 0)
2047                         continue;
2048
2049                 /* Found relid must not be in joinrelids. */
2050                 if (bms_is_member(relid, joinrelids))
2051                 {
2052                         parse_ereport(lhint->base.hint_str,
2053                                                   ("Relation name \"%s\" is duplicated.", relname));
2054                         lhint->base.state = HINT_STATE_ERROR;
2055                         bms_free(joinrelids);
2056                         return;
2057                 }
2058
2059                 /* Create bitmap of relids for current join level. */
2060                 joinrelids = bms_add_member(joinrelids, relid);
2061                 njoinrels++;
2062
2063                 /* We never have join method hint for single relation. */
2064                 if (njoinrels < 2)
2065                         continue;
2066
2067                 /*
2068                  * If we don't have join method hint, create new one for the
2069                  * join combination with all join methods are enabled.
2070                  */
2071                 hint = find_join_hint(joinrelids);
2072                 if (hint == NULL)
2073                 {
2074                         /*
2075                          * Here relnames is not set, since Relids bitmap is sufficient to
2076                          * control paths of this query afterward.
2077                          */
2078                         hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
2079                                                                                                                    HINT_LEADING);
2080                         hint->base.state = HINT_STATE_USED;
2081                         hint->nrels = njoinrels;
2082                         hint->enforce_mask = ENABLE_ALL_JOIN;
2083                         hint->joinrelids = bms_copy(joinrelids);
2084                 }
2085
2086                 join_method_hints[njoinrels] = hint;
2087
2088                 if (njoinrels >= nbaserel)
2089                         break;
2090         }
2091
2092         bms_free(joinrelids);
2093
2094         if (njoinrels < 2)
2095                 return;
2096
2097         /*
2098          * Delete all join hints which have different combination from Leading
2099          * hint.
2100          */
2101         for (i = 2; i <= njoinrels; i++)
2102         {
2103                 list_free(hstate->join_hint_level[i]);
2104
2105                 hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
2106         }
2107
2108         if (hint_state_enabled(lhint))
2109                 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
2110
2111         lhint->base.state = HINT_STATE_USED;
2112
2113 }
2114
2115 /*
2116  * set_plain_rel_pathlist
2117  *        Build access paths for a plain relation (no subquery, no inheritance)
2118  *
2119  * This function was copied and edited from set_plain_rel_pathlist() in
2120  * src/backend/optimizer/path/allpaths.c
2121  */
2122 static void
2123 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
2124 {
2125         /* Consider sequential scan */
2126 #if PG_VERSION_NUM >= 90200
2127         add_path(rel, create_seqscan_path(root, rel, NULL));
2128 #else
2129         add_path(rel, create_seqscan_path(root, rel));
2130 #endif
2131
2132         /* Consider index scans */
2133         create_index_paths(root, rel);
2134
2135         /* Consider TID scans */
2136         create_tidscan_paths(root, rel);
2137
2138         /* Now find the cheapest of the paths for this rel */
2139         set_cheapest(rel);
2140 }
2141
2142 static void
2143 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
2144                                   List *initial_rels)
2145 {
2146         ListCell   *l;
2147
2148         foreach(l, initial_rels)
2149         {
2150                 RelOptInfo         *rel = (RelOptInfo *) lfirst(l);
2151                 RangeTblEntry  *rte;
2152                 ScanMethodHint *hint;
2153
2154                 /* Skip relations which we can't choose scan method. */
2155                 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2156                         continue;
2157
2158                 rte = root->simple_rte_array[rel->relid];
2159
2160                 /* We can't force scan method of foreign tables */
2161                 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2162                         continue;
2163
2164                 /*
2165                  * Create scan paths with GUC parameters which are at the beginning of
2166                  * planner if scan method hint is not specified, otherwise use
2167                  * specified hints and mark the hint as used.
2168                  */
2169                 if ((hint = find_scan_hint(root, rel)) == NULL)
2170                         set_scan_config_options(hstate->init_scan_mask,
2171                                                                         hstate->context);
2172                 else
2173                 {
2174                         set_scan_config_options(hint->enforce_mask, hstate->context);
2175                         hint->base.state = HINT_STATE_USED;
2176                 }
2177
2178                 list_free_deep(rel->pathlist);
2179                 rel->pathlist = NIL;
2180                 if (rte->inh)
2181                 {
2182                         /* It's an "append relation", process accordingly */
2183                         set_append_rel_pathlist(root, rel, rel->relid, rte);
2184                 }
2185                 else
2186                 {
2187                         set_plain_rel_pathlist(root, rel, rte);
2188                 }
2189         }
2190
2191         /*
2192          * Restore the GUC variables we set above.
2193          */
2194         set_scan_config_options(hstate->init_scan_mask, hstate->context);
2195 }
2196
2197 /*
2198  * wrapper of make_join_rel()
2199  *
2200  * call make_join_rel() after changing enable_* parameters according to given
2201  * hints.
2202  */
2203 static RelOptInfo *
2204 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
2205 {
2206         Relids                  joinrelids;
2207         JoinMethodHint *hint;
2208         RelOptInfo         *rel;
2209         int                             save_nestlevel;
2210
2211         joinrelids = bms_union(rel1->relids, rel2->relids);
2212         hint = find_join_hint(joinrelids);
2213         bms_free(joinrelids);
2214
2215         if (!hint)
2216                 return pg_hint_plan_make_join_rel(root, rel1, rel2);
2217
2218         save_nestlevel = NewGUCNestLevel();
2219
2220         set_join_config_options(hint->enforce_mask, current_hint->context);
2221
2222         rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
2223         hint->base.state = HINT_STATE_USED;
2224
2225         /*
2226          * Restore the GUC variables we set above.
2227          */
2228         AtEOXact_GUC(true, save_nestlevel);
2229
2230         return rel;
2231 }
2232
2233 static int
2234 get_num_baserels(List *initial_rels)
2235 {
2236         int                     nbaserel = 0;
2237         ListCell   *l;
2238
2239         foreach(l, initial_rels)
2240         {
2241                 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2242
2243                 if (rel->reloptkind == RELOPT_BASEREL)
2244                         nbaserel++;
2245                 else if (rel->reloptkind ==RELOPT_JOINREL)
2246                         nbaserel+= bms_num_members(rel->relids);
2247                 else
2248                 {
2249                         /* other values not expected here */
2250                         elog(ERROR, "Unrecognized reloptkind type: %d", rel->reloptkind);
2251                 }
2252         }
2253
2254         return nbaserel;
2255 }
2256
2257 static RelOptInfo *
2258 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
2259                                                  List *initial_rels)
2260 {
2261         JoinMethodHint **join_method_hints;
2262         int                     nbaserel;
2263         RelOptInfo *rel;
2264         int                     i;
2265
2266         /*
2267          * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
2268          * valid hint is supplied.
2269          */
2270         if (!current_hint)
2271         {
2272                 if (prev_join_search)
2273                         return (*prev_join_search) (root, levels_needed, initial_rels);
2274                 else if (enable_geqo && levels_needed >= geqo_threshold)
2275                         return geqo(root, levels_needed, initial_rels);
2276                 else
2277                         return standard_join_search(root, levels_needed, initial_rels);
2278         }
2279
2280         /* We apply scan method hint rebuild scan path. */
2281         rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
2282
2283         /*
2284          * In the case using GEQO, only scan method hints and Set hints have
2285          * effect.  Join method and join order is not controllable by hints.
2286          */
2287         if (enable_geqo && levels_needed >= geqo_threshold)
2288                 return geqo(root, levels_needed, initial_rels);
2289
2290         nbaserel = get_num_baserels(initial_rels);
2291         current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
2292         join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
2293
2294         transform_join_hints(current_hint, root, nbaserel, initial_rels,
2295                                                  join_method_hints);
2296
2297         rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
2298
2299         for (i = 2; i <= nbaserel; i++)
2300         {
2301                 list_free(current_hint->join_hint_level[i]);
2302
2303                 /* free Leading hint only */
2304                 if (join_method_hints[i] != NULL &&
2305                         join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
2306                         JoinMethodHintDelete(join_method_hints[i]);
2307         }
2308         pfree(current_hint->join_hint_level);
2309         pfree(join_method_hints);
2310
2311         if (current_hint->num_hints[HINT_TYPE_LEADING] > 0 &&
2312                 hint_state_enabled(current_hint->leading_hint))
2313                 set_join_config_options(current_hint->init_join_mask,
2314                                                                 current_hint->context);
2315
2316         return rel;
2317 }
2318
2319 /*
2320  * set_rel_pathlist
2321  *        Build access paths for a base relation
2322  *
2323  * This function was copied and edited from set_rel_pathlist() in
2324  * src/backend/optimizer/path/allpaths.c
2325  */
2326 static void
2327 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
2328                                  Index rti, RangeTblEntry *rte)
2329 {
2330 #if PG_VERSION_NUM >= 90200
2331         if (IS_DUMMY_REL(rel))
2332         {
2333                 /* We already proved the relation empty, so nothing more to do */
2334         }
2335         else if (rte->inh)
2336 #else
2337         if (rte->inh)
2338 #endif
2339         {
2340                 /* It's an "append relation", process accordingly */
2341                 set_append_rel_pathlist(root, rel, rti, rte);
2342         }
2343         else
2344         {
2345                 if (rel->rtekind == RTE_RELATION)
2346                 {
2347                         if (rte->relkind == RELKIND_RELATION)
2348                         {
2349                                 /* Plain relation */
2350                                 set_plain_rel_pathlist(root, rel, rte);
2351                         }
2352                         else
2353                                 elog(ERROR, "Unexpected relkind: %c", rte->relkind);
2354                 }
2355                 else
2356                         elog(ERROR, "Unexpected rtekind: %d", (int) rel->rtekind);
2357         }
2358 }
2359
2360 #define standard_join_search pg_hint_plan_standard_join_search
2361 #define join_search_one_level pg_hint_plan_join_search_one_level
2362 #define make_join_rel make_join_rel_wrapper
2363 #include "core.c"
2364
2365 #undef make_join_rel
2366 #define make_join_rel pg_hint_plan_make_join_rel
2367 #define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
2368 do { \
2369         ScanMethodHint *hint = NULL; \
2370         if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
2371         { \
2372                 set_scan_config_options(hint->enforce_mask, current_hint->context); \
2373                 hint->base.state = HINT_STATE_USED; \
2374         } \
2375         add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
2376         if (hint != NULL) \
2377                 set_scan_config_options(current_hint->init_scan_mask, current_hint->context); \
2378 } while(0)
2379 #include "make_join_rel.c"