OSDN Git Service

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