OSDN Git Service

memcpy()を使って文字列をコピーしていた部分をstrcpy()に修正した。
[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-2013, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
8  *
9  *-------------------------------------------------------------------------
10  */
11 #include "postgres.h"
12 #include "catalog/pg_collation.h"
13 #include "catalog/pg_index.h"
14 #include "commands/prepare.h"
15 #include "mb/pg_wchar.h"
16 #include "miscadmin.h"
17 #include "nodes/nodeFuncs.h"
18 #include "optimizer/clauses.h"
19 #include "optimizer/cost.h"
20 #include "optimizer/geqo.h"
21 #include "optimizer/joininfo.h"
22 #include "optimizer/pathnode.h"
23 #include "optimizer/paths.h"
24 #include "optimizer/plancat.h"
25 #include "optimizer/planner.h"
26 #include "optimizer/prep.h"
27 #include "optimizer/restrictinfo.h"
28 #include "parser/scansup.h"
29 #include "tcop/utility.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/memutils.h"
33 #include "utils/rel.h"
34 #include "utils/syscache.h"
35 #if PG_VERSION_NUM >= 90200
36 #include "catalog/pg_class.h"
37 #endif
38
39 #include "executor/spi.h"
40 #include "catalog/pg_type.h"
41
42 #ifdef PG_MODULE_MAGIC
43 PG_MODULE_MAGIC;
44 #endif
45
46 #if PG_VERSION_NUM < 90100
47 #error unsupported PostgreSQL version
48 #endif
49
50 #define BLOCK_COMMENT_START             "/*"
51 #define BLOCK_COMMENT_END               "*/"
52 #define HINT_COMMENT_KEYWORD    "+"
53 #define HINT_START                              BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
54 #define HINT_END                                BLOCK_COMMENT_END
55
56 /* hint keywords */
57 #define HINT_SEQSCAN                    "SeqScan"
58 #define HINT_INDEXSCAN                  "IndexScan"
59 #define HINT_INDEXSCANREGEXP    "IndexScanRegexp"
60 #define HINT_BITMAPSCAN                 "BitmapScan"
61 #define HINT_BITMAPSCANREGEXP   "BitmapScanRegexp"
62 #define HINT_TIDSCAN                    "TidScan"
63 #define HINT_NOSEQSCAN                  "NoSeqScan"
64 #define HINT_NOINDEXSCAN                "NoIndexScan"
65 #define HINT_NOBITMAPSCAN               "NoBitmapScan"
66 #define HINT_NOTIDSCAN                  "NoTidScan"
67 #if PG_VERSION_NUM >= 90200
68 #define HINT_INDEXONLYSCAN              "IndexOnlyScan"
69 #define HINT_INDEXONLYSCANREGEXP        "IndexOnlyScanRegexp"
70 #define HINT_NOINDEXONLYSCAN    "NoIndexOnlyScan"
71 #endif
72 #define HINT_NESTLOOP                   "NestLoop"
73 #define HINT_MERGEJOIN                  "MergeJoin"
74 #define HINT_HASHJOIN                   "HashJoin"
75 #define HINT_NONESTLOOP                 "NoNestLoop"
76 #define HINT_NOMERGEJOIN                "NoMergeJoin"
77 #define HINT_NOHASHJOIN                 "NoHashJoin"
78 #define HINT_LEADING                    "Leading"
79 #define HINT_SET                                "Set"
80
81 #define HINT_ARRAY_DEFAULT_INITSIZE 8
82
83 #define hint_ereport(str, detail) \
84         ereport(pg_hint_plan_parse_messages, \
85                         (errmsg("hint syntax error at or near \"%s\"", (str)), \
86                          errdetail detail))
87
88 #define skip_space(str) \
89         while (isspace(*str)) \
90                 str++;
91
92 enum
93 {
94         ENABLE_SEQSCAN = 0x01,
95         ENABLE_INDEXSCAN = 0x02,
96         ENABLE_BITMAPSCAN = 0x04,
97         ENABLE_TIDSCAN = 0x08,
98 #if PG_VERSION_NUM >= 90200
99         ENABLE_INDEXONLYSCAN = 0x10
100 #endif
101 } SCAN_TYPE_BITS;
102
103 enum
104 {
105         ENABLE_NESTLOOP = 0x01,
106         ENABLE_MERGEJOIN = 0x02,
107         ENABLE_HASHJOIN = 0x04
108 } JOIN_TYPE_BITS;
109
110 #if PG_VERSION_NUM >= 90200
111 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
112                                                  ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
113                                                  ENABLE_INDEXONLYSCAN)
114 #else
115 #define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
116                                                  ENABLE_BITMAPSCAN | ENABLE_TIDSCAN)
117 #endif
118 #define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
119 #define DISABLE_ALL_SCAN 0
120 #define DISABLE_ALL_JOIN 0
121
122 /* hint keyword of enum type*/
123 typedef enum HintKeyword
124 {
125         HINT_KEYWORD_SEQSCAN,
126         HINT_KEYWORD_INDEXSCAN,
127         HINT_KEYWORD_INDEXSCANREGEXP,
128         HINT_KEYWORD_BITMAPSCAN,
129         HINT_KEYWORD_BITMAPSCANREGEXP,
130         HINT_KEYWORD_TIDSCAN,
131         HINT_KEYWORD_NOSEQSCAN,
132         HINT_KEYWORD_NOINDEXSCAN,
133         HINT_KEYWORD_NOBITMAPSCAN,
134         HINT_KEYWORD_NOTIDSCAN,
135 #if PG_VERSION_NUM >= 90200
136         HINT_KEYWORD_INDEXONLYSCAN,
137         HINT_KEYWORD_INDEXONLYSCANREGEXP,
138         HINT_KEYWORD_NOINDEXONLYSCAN,
139 #endif
140         HINT_KEYWORD_NESTLOOP,
141         HINT_KEYWORD_MERGEJOIN,
142         HINT_KEYWORD_HASHJOIN,
143         HINT_KEYWORD_NONESTLOOP,
144         HINT_KEYWORD_NOMERGEJOIN,
145         HINT_KEYWORD_NOHASHJOIN,
146         HINT_KEYWORD_LEADING,
147         HINT_KEYWORD_SET,
148         HINT_KEYWORD_UNRECOGNIZED
149 } HintKeyword;
150
151 typedef struct Hint Hint;
152 typedef struct HintState HintState;
153
154 typedef Hint *(*HintCreateFunction) (const char *hint_str,
155                                                                          const char *keyword,
156                                                                          HintKeyword hint_keyword);
157 typedef void (*HintDeleteFunction) (Hint *hint);
158 typedef void (*HintDescFunction) (Hint *hint, StringInfo buf);
159 typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
160 typedef const char *(*HintParseFunction) (Hint *hint, HintState *hstate,
161                                                                                   Query *parse, const char *str);
162
163 /* hint types */
164 #define NUM_HINT_TYPE   4
165 typedef enum HintType
166 {
167         HINT_TYPE_SCAN_METHOD,
168         HINT_TYPE_JOIN_METHOD,
169         HINT_TYPE_LEADING,
170         HINT_TYPE_SET
171 } HintType;
172
173 static const char *HintTypeName[] = {
174         "scan method",
175         "join method",
176         "leading",
177         "set"
178 };
179
180 /* hint status */
181 typedef enum HintStatus
182 {
183         HINT_STATE_NOTUSED = 0,         /* specified relation not used in query */
184         HINT_STATE_USED,                        /* hint is used */
185         HINT_STATE_DUPLICATION,         /* specified hint duplication */
186         HINT_STATE_ERROR                        /* execute error (parse error does not include
187                                                                  * it) */
188 } HintStatus;
189
190 #define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
191                                                                   (hint)->base.state == HINT_STATE_USED)
192
193 /* common data for all hints. */
194 struct Hint
195 {
196         const char                 *hint_str;           /* must not do pfree */
197         const char                 *keyword;            /* must not do pfree */
198         HintKeyword                     hint_keyword;
199         HintType                        type;
200         HintStatus                      state;
201         HintDeleteFunction      delete_func;
202         HintDescFunction        desc_func;
203         HintCmpFunction         cmp_func;
204         HintParseFunction       parse_func;
205 };
206
207 /* scan method hints */
208 typedef struct ScanMethodHint
209 {
210         Hint                    base;
211         char               *relname;
212         List               *indexnames;
213         bool                    regexp;
214         unsigned char   enforce_mask;
215 } ScanMethodHint;
216
217 typedef struct ParentIndexInfo
218 {
219         bool            indisunique;
220         Oid                     method;
221         List       *column_names;
222         char       *expression_str;
223         Oid                *indcollation;
224         Oid                *opclass;
225         int16      *indoption;
226         char       *indpred_str;
227 } ParentIndexInfo;
228
229 /* join method hints */
230 typedef struct JoinMethodHint
231 {
232         Hint                    base;
233         int                             nrels;
234         int                             inner_nrels;
235         char              **relnames;
236         unsigned char   enforce_mask;
237         Relids                  joinrelids;
238         Relids                  inner_joinrelids;
239 } JoinMethodHint;
240
241 /* join order hints */
242 typedef struct OuterInnerRels
243 {
244         char   *relation;
245         List   *outer_inner_pair;
246 } OuterInnerRels;
247
248 typedef struct LeadingHint
249 {
250         Hint                    base;
251         List               *relations;  /* relation names specified in Leading hint */
252         OuterInnerRels *outer_inner;
253 } LeadingHint;
254
255 /* change a run-time parameter hints */
256 typedef struct SetHint
257 {
258         Hint    base;
259         char   *name;                           /* name of variable */
260         char   *value;
261         List   *words;
262 } SetHint;
263
264 /*
265  * Describes a context of hint processing.
266  */
267 struct HintState
268 {
269         char               *hint_str;                   /* original hint string */
270
271         /* all hint */
272         int                             nall_hints;                     /* # of valid all hints */
273         int                             max_all_hints;          /* # of slots for all hints */
274         Hint              **all_hints;                  /* parsed all hints */
275
276         /* # of each hints */
277         int                             num_hints[NUM_HINT_TYPE];
278
279         /* for scan method hints */
280         ScanMethodHint **scan_hints;            /* parsed scan hints */
281         int                             init_scan_mask;         /* initial value scan parameter */
282         Index                   parent_relid;           /* inherit parent table relid */
283         Oid                             parent_rel_oid;     /* inherit parent table relid */
284         ScanMethodHint *parent_hint;            /* inherit parent table scan hint */
285         List               *parent_index_infos; /* infomation of inherit parent table's
286                                                                                  * index */
287
288         /* for join method hints */
289         JoinMethodHint **join_hints;            /* parsed join hints */
290         int                             init_join_mask;         /* initial value join parameter */
291         List              **join_hint_level;
292
293         /* for Leading hint */
294         LeadingHint       **leading_hint;               /* parsed Leading hints */
295
296         /* for Set hints */
297         SetHint           **set_hints;                  /* parsed Set hints */
298         GucContext              context;                        /* which GUC parameters can we set? */
299 };
300
301 /*
302  * Describes a hint parser module which is bound with particular hint keyword.
303  */
304 typedef struct HintParser
305 {
306         char                       *keyword;
307         HintCreateFunction      create_func;
308         HintKeyword                     hint_keyword;
309 } HintParser;
310
311 /* Module callbacks */
312 void            _PG_init(void);
313 void            _PG_fini(void);
314
315 static void push_hint(HintState *hstate);
316 static void pop_hint(void);
317
318 static void pg_hint_plan_ProcessUtility(Node *parsetree,
319                                                                                 const char *queryString,
320                                                                                 ParamListInfo params, bool isTopLevel,
321                                                                                 DestReceiver *dest,
322                                                                                 char *completionTag);
323 static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
324                                                                                  ParamListInfo boundParams);
325 static void pg_hint_plan_get_relation_info(PlannerInfo *root,
326                                                                                    Oid relationObjectId,
327                                                                                    bool inhparent, RelOptInfo *rel);
328 static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
329                                                                                         int levels_needed,
330                                                                                         List *initial_rels);
331
332 static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
333                                                                   HintKeyword hint_keyword);
334 static void ScanMethodHintDelete(ScanMethodHint *hint);
335 static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf);
336 static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
337 static const char *ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate,
338                                                                            Query *parse, const char *str);
339 static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
340                                                                   HintKeyword hint_keyword);
341 static void JoinMethodHintDelete(JoinMethodHint *hint);
342 static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf);
343 static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
344 static const char *JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate,
345                                                                            Query *parse, const char *str);
346 static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
347                                                            HintKeyword hint_keyword);
348 static void LeadingHintDelete(LeadingHint *hint);
349 static void LeadingHintDesc(LeadingHint *hint, StringInfo buf);
350 static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
351 static const char *LeadingHintParse(LeadingHint *hint, HintState *hstate,
352                                                                         Query *parse, const char *str);
353 static Hint *SetHintCreate(const char *hint_str, const char *keyword,
354                                                    HintKeyword hint_keyword);
355 static void SetHintDelete(SetHint *hint);
356 static void SetHintDesc(SetHint *hint, StringInfo buf);
357 static int SetHintCmp(const SetHint *a, const SetHint *b);
358 static const char *SetHintParse(SetHint *hint, HintState *hstate, Query *parse,
359                                                                 const char *str);
360
361 static void quote_value(StringInfo buf, const char *value);
362
363 static const char *parse_quoted_value(const char *str, char **word,
364                                                                           bool truncate);
365
366 RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
367                                                                                           int levels_needed,
368                                                                                           List *initial_rels);
369 void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
370 static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
371                                                                           ListCell *other_rels);
372 static void make_rels_by_clauseless_joins(PlannerInfo *root,
373                                                                                   RelOptInfo *old_rel,
374                                                                                   ListCell *other_rels);
375 static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
376 static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
377                                                                         Index rti, RangeTblEntry *rte);
378 #if PG_VERSION_NUM >= 90200
379 static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel,
380                                                    List *live_childrels,
381                                                    List *all_child_pathkeys);
382 #endif
383 static List *accumulate_append_subpath(List *subpaths, Path *path);
384 #if PG_VERSION_NUM < 90200
385 static void set_dummy_rel_pathlist(RelOptInfo *rel);
386 #endif
387 RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
388                                                                            RelOptInfo *rel2);
389
390 /* GUC variables */
391 static bool     pg_hint_plan_enable_hint = true;
392 static bool     pg_hint_plan_debug_print = false;
393 static int      pg_hint_plan_parse_messages = INFO;
394
395 static const struct config_enum_entry parse_messages_level_options[] = {
396         {"debug", DEBUG2, true},
397         {"debug5", DEBUG5, false},
398         {"debug4", DEBUG4, false},
399         {"debug3", DEBUG3, false},
400         {"debug2", DEBUG2, false},
401         {"debug1", DEBUG1, false},
402         {"log", LOG, false},
403         {"info", INFO, false},
404         {"notice", NOTICE, false},
405         {"warning", WARNING, false},
406         {"error", ERROR, false},
407         /*
408          * {"fatal", FATAL, true},
409          * {"panic", PANIC, true},
410          */
411         {NULL, 0, false}
412 };
413
414 /* Saved hook values in case of unload */
415 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
416 static planner_hook_type prev_planner = NULL;
417 static get_relation_info_hook_type prev_get_relation_info = NULL;
418 static join_search_hook_type prev_join_search = NULL;
419
420 /* Hold reference to currently active hint */
421 static HintState *current_hint = NULL;
422
423 /*
424  * List of hint contexts.  We treat the head of the list as the Top of the
425  * context stack, so current_hint always points the first element of this list.
426  */
427 static List *HintStateStack = NIL;
428
429 /*
430  * Holds statement name during executing EXECUTE command.  NULL for other
431  * statements.
432  */
433 static char        *stmt_name = NULL;
434
435 static const HintParser parsers[] = {
436         {HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
437         {HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
438         {HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
439         {HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
440         {HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
441          HINT_KEYWORD_BITMAPSCANREGEXP},
442         {HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
443         {HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
444         {HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
445         {HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
446         {HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
447 #if PG_VERSION_NUM >= 90200
448         {HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
449         {HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
450          HINT_KEYWORD_INDEXONLYSCANREGEXP},
451         {HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
452 #endif
453         {HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
454         {HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
455         {HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
456         {HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
457         {HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
458         {HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
459         {HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
460         {HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
461         {NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
462 };
463
464 /*
465  * Module load callbacks
466  */
467 void
468 _PG_init(void)
469 {
470         /* Define custom GUC variables. */
471         DefineCustomBoolVariable("pg_hint_plan.enable_hint",
472                          "Force planner to use plans specified in the hint comment preceding to the query.",
473                                                          NULL,
474                                                          &pg_hint_plan_enable_hint,
475                                                          true,
476                                                          PGC_USERSET,
477                                                          0,
478                                                          NULL,
479                                                          NULL,
480                                                          NULL);
481
482         DefineCustomBoolVariable("pg_hint_plan.debug_print",
483                                                          "Logs results of hint parsing.",
484                                                          NULL,
485                                                          &pg_hint_plan_debug_print,
486                                                          false,
487                                                          PGC_USERSET,
488                                                          0,
489                                                          NULL,
490                                                          NULL,
491                                                          NULL);
492
493         DefineCustomEnumVariable("pg_hint_plan.parse_messages",
494                                                          "Message level of parse errors.",
495                                                          NULL,
496                                                          &pg_hint_plan_parse_messages,
497                                                          INFO,
498                                                          parse_messages_level_options,
499                                                          PGC_USERSET,
500                                                          0,
501                                                          NULL,
502                                                          NULL,
503                                                          NULL);
504
505         /* Install hooks. */
506         prev_ProcessUtility = ProcessUtility_hook;
507         ProcessUtility_hook = pg_hint_plan_ProcessUtility;
508         prev_planner = planner_hook;
509         planner_hook = pg_hint_plan_planner;
510         prev_get_relation_info = get_relation_info_hook;
511         get_relation_info_hook = pg_hint_plan_get_relation_info;
512         prev_join_search = join_search_hook;
513         join_search_hook = pg_hint_plan_join_search;
514 }
515
516 /*
517  * Module unload callback
518  * XXX never called
519  */
520 void
521 _PG_fini(void)
522 {
523         /* Uninstall hooks. */
524         ProcessUtility_hook = prev_ProcessUtility;
525         planner_hook = prev_planner;
526         get_relation_info_hook = prev_get_relation_info;
527         join_search_hook = prev_join_search;
528 }
529
530 /*
531  * create and delete functions the hint object
532  */
533
534 static Hint *
535 ScanMethodHintCreate(const char *hint_str, const char *keyword,
536                                          HintKeyword hint_keyword)
537 {
538         ScanMethodHint *hint;
539
540         hint = palloc(sizeof(ScanMethodHint));
541         hint->base.hint_str = hint_str;
542         hint->base.keyword = keyword;
543         hint->base.hint_keyword = hint_keyword;
544         hint->base.type = HINT_TYPE_SCAN_METHOD;
545         hint->base.state = HINT_STATE_NOTUSED;
546         hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
547         hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
548         hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
549         hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
550         hint->relname = NULL;
551         hint->indexnames = NIL;
552         hint->regexp = false;
553         hint->enforce_mask = 0;
554
555         return (Hint *) hint;
556 }
557
558 static void
559 ScanMethodHintDelete(ScanMethodHint *hint)
560 {
561         if (!hint)
562                 return;
563
564         if (hint->relname)
565                 pfree(hint->relname);
566         list_free_deep(hint->indexnames);
567         pfree(hint);
568 }
569
570 static Hint *
571 JoinMethodHintCreate(const char *hint_str, const char *keyword,
572                                          HintKeyword hint_keyword)
573 {
574         JoinMethodHint *hint;
575
576         hint = palloc(sizeof(JoinMethodHint));
577         hint->base.hint_str = hint_str;
578         hint->base.keyword = keyword;
579         hint->base.hint_keyword = hint_keyword;
580         hint->base.type = HINT_TYPE_JOIN_METHOD;
581         hint->base.state = HINT_STATE_NOTUSED;
582         hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
583         hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
584         hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
585         hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
586         hint->nrels = 0;
587         hint->inner_nrels = 0;
588         hint->relnames = NULL;
589         hint->enforce_mask = 0;
590         hint->joinrelids = NULL;
591         hint->inner_joinrelids = NULL;
592
593         return (Hint *) hint;
594 }
595
596 static void
597 JoinMethodHintDelete(JoinMethodHint *hint)
598 {
599         if (!hint)
600                 return;
601
602         if (hint->relnames)
603         {
604                 int     i;
605
606                 for (i = 0; i < hint->nrels; i++)
607                         pfree(hint->relnames[i]);
608                 pfree(hint->relnames);
609         }
610
611         bms_free(hint->joinrelids);
612         bms_free(hint->inner_joinrelids);
613         pfree(hint);
614 }
615
616 static Hint *
617 LeadingHintCreate(const char *hint_str, const char *keyword,
618                                   HintKeyword hint_keyword)
619 {
620         LeadingHint        *hint;
621
622         hint = palloc(sizeof(LeadingHint));
623         hint->base.hint_str = hint_str;
624         hint->base.keyword = keyword;
625         hint->base.hint_keyword = hint_keyword;
626         hint->base.type = HINT_TYPE_LEADING;
627         hint->base.state = HINT_STATE_NOTUSED;
628         hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
629         hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
630         hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
631         hint->base.parse_func = (HintParseFunction) LeadingHintParse;
632         hint->relations = NIL;
633         hint->outer_inner = NULL;
634
635         return (Hint *) hint;
636 }
637
638 static void
639 LeadingHintDelete(LeadingHint *hint)
640 {
641         if (!hint)
642                 return;
643
644         list_free_deep(hint->relations);
645         if (hint->outer_inner)
646                 pfree(hint->outer_inner);
647         pfree(hint);
648 }
649
650 static Hint *
651 SetHintCreate(const char *hint_str, const char *keyword,
652                           HintKeyword hint_keyword)
653 {
654         SetHint    *hint;
655
656         hint = palloc(sizeof(SetHint));
657         hint->base.hint_str = hint_str;
658         hint->base.keyword = keyword;
659         hint->base.hint_keyword = hint_keyword;
660         hint->base.type = HINT_TYPE_SET;
661         hint->base.state = HINT_STATE_NOTUSED;
662         hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
663         hint->base.desc_func = (HintDescFunction) SetHintDesc;
664         hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
665         hint->base.parse_func = (HintParseFunction) SetHintParse;
666         hint->name = NULL;
667         hint->value = NULL;
668         hint->words = NIL;
669
670         return (Hint *) hint;
671 }
672
673 static void
674 SetHintDelete(SetHint *hint)
675 {
676         if (!hint)
677                 return;
678
679         if (hint->name)
680                 pfree(hint->name);
681         if (hint->value)
682                 pfree(hint->value);
683         if (hint->words)
684                 list_free(hint->words);
685         pfree(hint);
686 }
687
688 static HintState *
689 HintStateCreate(void)
690 {
691         HintState   *hstate;
692
693         hstate = palloc(sizeof(HintState));
694         hstate->hint_str = NULL;
695         hstate->nall_hints = 0;
696         hstate->max_all_hints = 0;
697         hstate->all_hints = NULL;
698         memset(hstate->num_hints, 0, sizeof(hstate->num_hints));
699         hstate->scan_hints = NULL;
700         hstate->init_scan_mask = 0;
701         hstate->parent_relid = 0;
702         hstate->parent_rel_oid = InvalidOid;
703         hstate->parent_hint = NULL;
704         hstate->parent_index_infos = NIL;
705         hstate->join_hints = NULL;
706         hstate->init_join_mask = 0;
707         hstate->join_hint_level = NULL;
708         hstate->leading_hint = NULL;
709         hstate->context = superuser() ? PGC_SUSET : PGC_USERSET;
710         hstate->set_hints = NULL;
711
712         return hstate;
713 }
714
715 static void
716 HintStateDelete(HintState *hstate)
717 {
718         int                     i;
719
720         if (!hstate)
721                 return;
722
723         if (hstate->hint_str)
724                 pfree(hstate->hint_str);
725
726         for (i = 0; i < hstate->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
727                 hstate->all_hints[i]->delete_func(hstate->all_hints[i]);
728         if (hstate->all_hints)
729                 pfree(hstate->all_hints);
730         if (hstate->parent_index_infos)
731                 list_free(hstate->parent_index_infos);
732 }
733
734 /*
735  * Copy given value into buf, with quoting with '"' if necessary.
736  */
737 static void
738 quote_value(StringInfo buf, const char *value)
739 {
740         bool            need_quote = false;
741         const char *str;
742
743         for (str = value; *str != '\0'; str++)
744         {
745                 if (isspace(*str) || *str == '(' || *str == ')' || *str == '"')
746                 {
747                         need_quote = true;
748                         appendStringInfoCharMacro(buf, '"');
749                         break;
750                 }
751         }
752
753         for (str = value; *str != '\0'; str++)
754         {
755                 if (*str == '"')
756                         appendStringInfoCharMacro(buf, '"');
757
758                 appendStringInfoCharMacro(buf, *str);
759         }
760
761         if (need_quote)
762                 appendStringInfoCharMacro(buf, '"');
763 }
764
765 static void
766 ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf)
767 {
768         ListCell   *l;
769
770         appendStringInfo(buf, "%s(", hint->base.keyword);
771         if (hint->relname != NULL)
772         {
773                 quote_value(buf, hint->relname);
774                 foreach(l, hint->indexnames)
775                 {
776                         appendStringInfoCharMacro(buf, ' ');
777                         quote_value(buf, (char *) lfirst(l));
778                 }
779         }
780         appendStringInfoString(buf, ")\n");
781 }
782
783 static void
784 JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf)
785 {
786         int     i;
787
788         appendStringInfo(buf, "%s(", hint->base.keyword);
789         if (hint->relnames != NULL)
790         {
791                 quote_value(buf, hint->relnames[0]);
792                 for (i = 1; i < hint->nrels; i++)
793                 {
794                         appendStringInfoCharMacro(buf, ' ');
795                         quote_value(buf, hint->relnames[i]);
796                 }
797         }
798         appendStringInfoString(buf, ")\n");
799
800 }
801
802 static void
803 OuterInnerDesc(OuterInnerRels *outer_inner, StringInfo buf)
804 {
805         if (outer_inner->relation == NULL)
806         {
807                 bool            is_first;
808                 ListCell   *l;
809
810                 is_first = true;
811
812                 appendStringInfoCharMacro(buf, '(');
813                 foreach(l, outer_inner->outer_inner_pair)
814                 {
815                         if (is_first)
816                                 is_first = false;
817                         else
818                                 appendStringInfoCharMacro(buf, ' ');
819
820                         OuterInnerDesc(lfirst(l), buf);
821                 }
822
823                 appendStringInfoCharMacro(buf, ')');
824         }
825         else
826                 quote_value(buf, outer_inner->relation);
827 }
828
829 static void
830 LeadingHintDesc(LeadingHint *hint, StringInfo buf)
831 {
832         appendStringInfo(buf, "%s(", HINT_LEADING);
833         if (hint->outer_inner == NULL)
834         {
835                 ListCell   *l;
836                 bool            is_first;
837
838                 is_first = true;
839
840                 foreach(l, hint->relations)
841                 {
842                         if (is_first)
843                                 is_first = false;
844                         else
845                                 appendStringInfoCharMacro(buf, ' ');
846
847                         quote_value(buf, (char *) lfirst(l));
848                 }
849         }
850         else
851                 OuterInnerDesc(hint->outer_inner, buf);
852
853         appendStringInfoString(buf, ")\n");
854 }
855
856 static void
857 SetHintDesc(SetHint *hint, StringInfo buf)
858 {
859         bool            is_first = true;
860         ListCell   *l;
861
862         appendStringInfo(buf, "%s(", HINT_SET);
863         foreach(l, hint->words)
864         {
865                 if (is_first)
866                         is_first = false;
867                 else
868                         appendStringInfoCharMacro(buf, ' ');
869
870                 quote_value(buf, (char *) lfirst(l));
871         }
872         appendStringInfo(buf, ")\n");
873 }
874
875 /*
876  * Append string which repserents all hints in a given state to buf, with
877  * preceding title with them.
878  */
879 static void
880 desc_hint_in_state(HintState *hstate, StringInfo buf, const char *title,
881                                         HintStatus state)
882 {
883         int     i;
884
885         appendStringInfo(buf, "%s:\n", title);
886         for (i = 0; i < hstate->nall_hints; i++)
887         {
888                 if (hstate->all_hints[i]->state != state)
889                         continue;
890
891                 hstate->all_hints[i]->desc_func(hstate->all_hints[i], buf);
892         }
893 }
894
895 /*
896  * Dump contents of given hstate to server log with log level LOG.
897  */
898 static void
899 HintStateDump(HintState *hstate)
900 {
901         StringInfoData  buf;
902
903         if (!hstate)
904         {
905                 elog(LOG, "pg_hint_plan:\nno hint");
906                 return;
907         }
908
909         initStringInfo(&buf);
910
911         appendStringInfoString(&buf, "pg_hint_plan:\n");
912         desc_hint_in_state(hstate, &buf, "used hint", HINT_STATE_USED);
913         desc_hint_in_state(hstate, &buf, "not used hint", HINT_STATE_NOTUSED);
914         desc_hint_in_state(hstate, &buf, "duplication hint", HINT_STATE_DUPLICATION);
915         desc_hint_in_state(hstate, &buf, "error hint", HINT_STATE_ERROR);
916
917         elog(LOG, "%s", buf.data);
918
919         pfree(buf.data);
920 }
921
922 /*
923  * compare functions
924  */
925
926 static int
927 RelnameCmp(const void *a, const void *b)
928 {
929         const char *relnamea = *((const char **) a);
930         const char *relnameb = *((const char **) b);
931
932         return strcmp(relnamea, relnameb);
933 }
934
935 static int
936 ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
937 {
938         return RelnameCmp(&a->relname, &b->relname);
939 }
940
941 static int
942 JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
943 {
944         int     i;
945
946         if (a->nrels != b->nrels)
947                 return a->nrels - b->nrels;
948
949         for (i = 0; i < a->nrels; i++)
950         {
951                 int     result;
952                 if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
953                         return result;
954         }
955
956         return 0;
957 }
958
959 static int
960 LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
961 {
962         return 0;
963 }
964
965 static int
966 SetHintCmp(const SetHint *a, const SetHint *b)
967 {
968         return strcmp(a->name, b->name);
969 }
970
971 static int
972 HintCmp(const void *a, const void *b)
973 {
974         const Hint *hinta = *((const Hint **) a);
975         const Hint *hintb = *((const Hint **) b);
976
977         if (hinta->type != hintb->type)
978                 return hinta->type - hintb->type;
979         if (hinta->state == HINT_STATE_ERROR)
980                 return -1;
981         if (hintb->state == HINT_STATE_ERROR)
982                 return 1;
983         return hinta->cmp_func(hinta, hintb);
984 }
985
986 /*
987  * Returns byte offset of hint b from hint a.  If hint a was specified before
988  * b, positive value is returned.
989  */
990 static int
991 HintCmpWithPos(const void *a, const void *b)
992 {
993         const Hint *hinta = *((const Hint **) a);
994         const Hint *hintb = *((const Hint **) b);
995         int             result;
996
997         result = HintCmp(a, b);
998         if (result == 0)
999                 result = hinta->hint_str - hintb->hint_str;
1000
1001         return result;
1002 }
1003
1004 /*
1005  * parse functions
1006  */
1007 static const char *
1008 parse_keyword(const char *str, StringInfo buf)
1009 {
1010         skip_space(str);
1011
1012         while (!isspace(*str) && *str != '(' && *str != '\0')
1013                 appendStringInfoCharMacro(buf, *str++);
1014
1015         return str;
1016 }
1017
1018 static const char *
1019 skip_parenthesis(const char *str, char parenthesis)
1020 {
1021         skip_space(str);
1022
1023         if (*str != parenthesis)
1024         {
1025                 if (parenthesis == '(')
1026                         hint_ereport(str, ("Opening parenthesis is necessary."));
1027                 else if (parenthesis == ')')
1028                         hint_ereport(str, ("Closing parenthesis is necessary."));
1029
1030                 return NULL;
1031         }
1032
1033         str++;
1034
1035         return str;
1036 }
1037
1038 /*
1039  * Parse a token from str, and store malloc'd copy into word.  A token can be
1040  * quoted with '"'.  Return value is pointer to unparsed portion of original
1041  * string, or NULL if an error occurred.
1042  *
1043  * Parsed token is truncated within NAMEDATALEN-1 bytes, when truncate is true.
1044  */
1045 static const char *
1046 parse_quoted_value(const char *str, char **word, bool truncate)
1047 {
1048         StringInfoData  buf;
1049         bool                    in_quote;
1050
1051         /* Skip leading spaces. */
1052         skip_space(str);
1053
1054         initStringInfo(&buf);
1055         if (*str == '"')
1056         {
1057                 str++;
1058                 in_quote = true;
1059         }
1060         else
1061                 in_quote = false;
1062
1063         while (true)
1064         {
1065                 if (in_quote)
1066                 {
1067                         /* Double quotation must be closed. */
1068                         if (*str == '\0')
1069                         {
1070                                 pfree(buf.data);
1071                                 hint_ereport(str, ("Unterminated quoted string."));
1072                                 return NULL;
1073                         }
1074
1075                         /*
1076                          * Skip escaped double quotation.
1077                          *
1078                          * We don't allow slash-asterisk and asterisk-slash (delimiters of
1079                          * block comments) to be an object name, so users must specify
1080                          * alias for such object names.
1081                          *
1082                          * Those special names can be allowed if we care escaped slashes
1083                          * and asterisks, but we don't.
1084                          */
1085                         if (*str == '"')
1086                         {
1087                                 str++;
1088                                 if (*str != '"')
1089                                         break;
1090                         }
1091                 }
1092                 else if (isspace(*str) || *str == '(' || *str == ')' || *str == '"' ||
1093                                  *str == '\0')
1094                         break;
1095
1096                 appendStringInfoCharMacro(&buf, *str++);
1097         }
1098
1099         if (buf.len == 0)
1100         {
1101                 hint_ereport(str, ("Zero-length delimited string."));
1102
1103                 pfree(buf.data);
1104
1105                 return NULL;
1106         }
1107
1108         /* Truncate name if it's too long */
1109         if (truncate)
1110                 truncate_identifier(buf.data, strlen(buf.data), true);
1111
1112         *word = buf.data;
1113
1114         return str;
1115 }
1116
1117 static OuterInnerRels *
1118 OuterInnerRelsCreate(char *name, List *outer_inner_list)
1119 {
1120         OuterInnerRels *outer_inner;
1121
1122         outer_inner = palloc(sizeof(OuterInnerRels));
1123         outer_inner->relation = name;
1124         outer_inner->outer_inner_pair = outer_inner_list;
1125
1126         return outer_inner;
1127 }
1128
1129 static const char *
1130 parse_parentheses_Leading_in(const char *str, OuterInnerRels **outer_inner)
1131 {
1132         List   *outer_inner_pair = NIL;
1133
1134         if ((str = skip_parenthesis(str, '(')) == NULL)
1135                 return NULL;
1136
1137         skip_space(str);
1138
1139         /* Store words in parentheses into outer_inner_list. */
1140         while(*str != ')' && *str != '\0')
1141         {
1142                 OuterInnerRels *outer_inner_rels;
1143
1144                 if (*str == '(')
1145                 {
1146                         str = parse_parentheses_Leading_in(str, &outer_inner_rels);
1147                         if (str == NULL)
1148                                 break;
1149                 }
1150                 else
1151                 {
1152                         char   *name;
1153
1154                         if ((str = parse_quoted_value(str, &name, true)) == NULL)
1155                                 break;
1156                         else
1157                                 outer_inner_rels = OuterInnerRelsCreate(name, NIL);
1158                 }
1159
1160                 outer_inner_pair = lappend(outer_inner_pair, outer_inner_rels);
1161                 skip_space(str);
1162         }
1163
1164         if (str == NULL ||
1165                 (str = skip_parenthesis(str, ')')) == NULL)
1166         {
1167                 list_free(outer_inner_pair);
1168                 return NULL;
1169         }
1170
1171         *outer_inner = OuterInnerRelsCreate(NULL, outer_inner_pair);
1172
1173         return str;
1174 }
1175
1176 static const char *
1177 parse_parentheses_Leading(const char *str, List **name_list,
1178         OuterInnerRels **outer_inner)
1179 {
1180         char   *name;
1181         bool    truncate = true;
1182
1183         if ((str = skip_parenthesis(str, '(')) == NULL)
1184                 return NULL;
1185
1186         skip_space(str);
1187         if (*str =='(')
1188         {
1189                 if ((str = parse_parentheses_Leading_in(str, outer_inner)) == NULL)
1190                         return NULL;
1191         }
1192         else
1193         {
1194                 /* Store words in parentheses into name_list. */
1195                 while(*str != ')' && *str != '\0')
1196                 {
1197                         if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1198                         {
1199                                 list_free(*name_list);
1200                                 return NULL;
1201                         }
1202
1203                         *name_list = lappend(*name_list, name);
1204                         skip_space(str);
1205                 }
1206         }
1207
1208         if ((str = skip_parenthesis(str, ')')) == NULL)
1209                 return NULL;
1210         return str;
1211 }
1212
1213 static const char *
1214 parse_parentheses(const char *str, List **name_list, HintKeyword keyword)
1215 {
1216         char   *name;
1217         bool    truncate = true;
1218
1219         if ((str = skip_parenthesis(str, '(')) == NULL)
1220                 return NULL;
1221
1222         skip_space(str);
1223
1224         /* Store words in parentheses into name_list. */
1225         while(*str != ')' && *str != '\0')
1226         {
1227                 if ((str = parse_quoted_value(str, &name, truncate)) == NULL)
1228                 {
1229                         list_free(*name_list);
1230                         return NULL;
1231                 }
1232
1233                 *name_list = lappend(*name_list, name);
1234                 skip_space(str);
1235
1236                 if (keyword == HINT_KEYWORD_INDEXSCANREGEXP ||
1237 #if PG_VERSION_NUM >= 90200
1238                         keyword == HINT_KEYWORD_INDEXONLYSCANREGEXP ||
1239 #endif
1240                         keyword == HINT_KEYWORD_BITMAPSCANREGEXP ||
1241                         keyword == HINT_KEYWORD_SET)
1242                 {
1243                         truncate = false;
1244                 }
1245         }
1246
1247         if ((str = skip_parenthesis(str, ')')) == NULL)
1248                 return NULL;
1249         return str;
1250 }
1251
1252 static void
1253 parse_hints(HintState *hstate, Query *parse, const char *str)
1254 {
1255         StringInfoData  buf;
1256         char               *head;
1257
1258         initStringInfo(&buf);
1259         while (*str != '\0')
1260         {
1261                 const HintParser *parser;
1262
1263                 /* in error message, we output the comment including the keyword. */
1264                 head = (char *) str;
1265
1266                 /* parse only the keyword of the hint. */
1267                 resetStringInfo(&buf);
1268                 str = parse_keyword(str, &buf);
1269
1270                 for (parser = parsers; parser->keyword != NULL; parser++)
1271                 {
1272                         char   *keyword = parser->keyword;
1273                         Hint   *hint;
1274
1275                         if (strcasecmp(buf.data, keyword) != 0)
1276                                 continue;
1277
1278                         hint = parser->create_func(head, keyword, parser->hint_keyword);
1279
1280                         /* parser of each hint does parse in a parenthesis. */
1281                         if ((str = hint->parse_func(hint, hstate, parse, str)) == NULL)
1282                         {
1283                                 hint->delete_func(hint);
1284                                 pfree(buf.data);
1285                                 return;
1286                         }
1287
1288                         /*
1289                          * Add hint information into all_hints array.  If we don't have
1290                          * enough space, double the array.
1291                          */
1292                         if (hstate->nall_hints == 0)
1293                         {
1294                                 hstate->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
1295                                 hstate->all_hints = (Hint **)
1296                                         palloc(sizeof(Hint *) * hstate->max_all_hints);
1297                         }
1298                         else if (hstate->nall_hints == hstate->max_all_hints)
1299                         {
1300                                 hstate->max_all_hints *= 2;
1301                                 hstate->all_hints = (Hint **)
1302                                         repalloc(hstate->all_hints,
1303                                                          sizeof(Hint *) * hstate->max_all_hints);
1304                         }
1305
1306                         hstate->all_hints[hstate->nall_hints] = hint;
1307                         hstate->nall_hints++;
1308
1309                         skip_space(str);
1310
1311                         break;
1312                 }
1313
1314                 if (parser->keyword == NULL)
1315                 {
1316                         hint_ereport(head,
1317                                                  ("Unrecognized hint keyword \"%s\".", buf.data));
1318                         pfree(buf.data);
1319                         return;
1320                 }
1321         }
1322
1323         pfree(buf.data);
1324 }
1325
1326
1327 /* 
1328  * Get hints from table by client-supplied query string and application name.
1329  */
1330 static const char *
1331 get_hints_from_table(const char *client_query, const char *client_application)
1332 {
1333         const char *search_query =
1334                 "SELECT hints "
1335                 "  FROM hint_plan.hints "
1336                 " WHERE norm_query_string = $1 "
1337                 "   AND ( application_name = $2 "
1338                 "    OR application_name = '' ) "
1339                 " ORDER BY application_name DESC";
1340         static SPIPlanPtr plan = NULL;
1341         int             ret;
1342         char   *hints = NULL;
1343         Oid             argtypes[2] = { TEXTOID, TEXTOID };
1344         Datum   values[2];
1345         bool    nulls[2] = { false, false };
1346         text   *qry;
1347         text   *app;
1348
1349         ret = SPI_connect();
1350         if (ret != SPI_OK_CONNECT)
1351                 elog(ERROR, "pg_hint_plan: SPI_connect => %d", ret);
1352
1353         if (plan == NULL)
1354         {
1355                 SPIPlanPtr      p;
1356                 p = SPI_prepare(search_query, 2, argtypes);
1357                 if (p == NULL)
1358                         elog(ERROR, "pg_hint_plan: SPI_prepare => %d", SPI_result);
1359                 plan = SPI_saveplan(p);
1360                 SPI_freeplan(p);
1361         }
1362
1363         qry = cstring_to_text(client_query);
1364         app = cstring_to_text(client_application);
1365         values[0] = PointerGetDatum(qry);
1366         values[1] = PointerGetDatum(app);
1367
1368         pg_hint_plan_enable_hint = false;
1369         ret = SPI_execute_plan(plan, values, nulls, true, 1);
1370         pg_hint_plan_enable_hint = true;
1371         if (ret != SPI_OK_SELECT)
1372                 elog(ERROR, "pg_hint_plan: SPI_execute_plan => %d", ret);
1373
1374         if (SPI_processed > 0)
1375         {
1376                 char    *buf;
1377
1378                 hints = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
1379                 /*
1380                  * SPI_connectで新しく作成されたメモリコンテキスト内で、pallocを
1381                  * 使用してメモリを確保してもSPI_finishで解放されてしまう。
1382                  * それを防ぐために、SPI_pallocを使って上位エクゼキュータコンテ
1383                  * キスト内にメモリを確保し、そこにヒント用テーブルから取得した
1384                  * ヒントを保存している。
1385                  */
1386                 buf = SPI_palloc(strlen(hints) + 1);
1387                 strcpy(buf, hints);
1388                 hints = buf;
1389         }
1390
1391         SPI_finish();
1392
1393         return hints;
1394 }
1395
1396 /*
1397  * Get client-supplied query string.
1398  */
1399 static const char *
1400 get_query_string(void)
1401 {
1402         const char *p;
1403
1404         if (stmt_name)
1405         {
1406                 PreparedStatement  *entry;
1407
1408                 entry = FetchPreparedStatement(stmt_name, true);
1409                 p = entry->plansource->query_string;
1410         }
1411         else
1412                 p = debug_query_string;
1413
1414         return p;
1415 }
1416
1417 /*
1418  * Get hints from the head block comment in client-supplied query string.
1419  */
1420 static const char *
1421 get_hints_from_comment(const char *p)
1422 {
1423         const char *hint_head;
1424         char       *head;
1425         char       *tail;
1426         int                     len;
1427
1428         if (p == NULL)
1429                 return NULL;
1430
1431         /* extract query head comment. */
1432         hint_head = strstr(p, HINT_START);
1433         if (hint_head == NULL)
1434                 return NULL;
1435         for (;p < hint_head; p++)
1436         {
1437                 /*
1438                  * Allow these characters precedes hint comment:
1439                  *   - digits
1440                  *   - alphabets which are in ASCII range
1441                  *   - space, tabs and new-lines
1442                  *   - underscores, for identifier
1443                  *   - commas, for SELECT clause, EXPLAIN and PREPARE
1444                  *   - parentheses, for EXPLAIN and PREPARE
1445                  *
1446                  * Note that we don't use isalpha() nor isalnum() in ctype.h here to
1447                  * avoid behavior which depends on locale setting.
1448                  */
1449                 if (!(*p >= '0' && *p <= '9') &&
1450                         !(*p >= 'A' && *p <= 'Z') &&
1451                         !(*p >= 'a' && *p <= 'z') &&
1452                         !isspace(*p) &&
1453                         *p != '_' &&
1454                         *p != ',' &&
1455                         *p != '(' && *p != ')')
1456                         return NULL;
1457         }
1458
1459         len = strlen(HINT_START);
1460         head = (char *) p;
1461         p += len;
1462         skip_space(p);
1463
1464         /* find hint end keyword. */
1465         if ((tail = strstr(p, HINT_END)) == NULL)
1466         {
1467                 hint_ereport(head, ("Unterminated block comment."));
1468                 return NULL;
1469         }
1470
1471         /* We don't support nested block comments. */
1472         if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
1473         {
1474                 hint_ereport(head, ("Nested block comments are not supported."));
1475                 return NULL;
1476         }
1477
1478         /* Make a copy of hint. */
1479         len = tail - p;
1480         head = palloc(len + 1);
1481         memcpy(head, p, len);
1482         head[len] = '\0';
1483         p = head;
1484
1485         return p;
1486 }
1487
1488 /*
1489  * Parse hints that got, create hint struct from parse tree and parse hints.
1490  */
1491 static HintState *
1492 create_hintstate(Query *parse, const char *hints)
1493 {
1494         const char *p;
1495         int                     i;
1496         HintState   *hstate;
1497
1498         if (hints == NULL)
1499                 return NULL;
1500
1501         p = hints;
1502         hstate = HintStateCreate();
1503         hstate->hint_str = (char *) hints;
1504
1505         /* parse each hint. */
1506         parse_hints(hstate, parse, p);
1507
1508         /* When nothing specified a hint, we free HintState and returns NULL. */
1509         if (hstate->nall_hints == 0)
1510         {
1511                 HintStateDelete(hstate);
1512                 return NULL;
1513         }
1514
1515         /* Sort hints in order of original position. */
1516         qsort(hstate->all_hints, hstate->nall_hints, sizeof(Hint *),
1517                   HintCmpWithPos);
1518
1519         /* Count number of hints per hint-type. */
1520         for (i = 0; i < hstate->nall_hints; i++)
1521         {
1522                 Hint   *cur_hint = hstate->all_hints[i];
1523                 hstate->num_hints[cur_hint->type]++;
1524         }
1525
1526         /*
1527          * If an object (or a set of objects) has multiple hints of same hint-type,
1528          * only the last hint is valid and others are igonred in planning.
1529          * Hints except the last are marked as 'duplicated' to remember the order.
1530          */
1531         for (i = 0; i < hstate->nall_hints - 1; i++)
1532         {
1533                 Hint   *cur_hint = hstate->all_hints[i];
1534                 Hint   *next_hint = hstate->all_hints[i + 1];
1535
1536                 /*
1537                  * Leading hint is marked as 'duplicated' in transform_join_hints.
1538                  */
1539                 if (cur_hint->type == HINT_TYPE_LEADING &&
1540                         next_hint->type == HINT_TYPE_LEADING)
1541                         continue;
1542
1543                 /*
1544                  * Note that we need to pass addresses of hint pointers, because
1545                  * HintCmp is designed to sort array of Hint* by qsort.
1546                  */
1547                 if (HintCmp(&cur_hint, &next_hint) == 0)
1548                 {
1549                         hint_ereport(cur_hint->hint_str,
1550                                                  ("Conflict %s hint.", HintTypeName[cur_hint->type]));
1551                         cur_hint->state = HINT_STATE_DUPLICATION;
1552                 }
1553         }
1554
1555         /*
1556          * Make sure that per-type array pointers point proper position in the
1557          * array which consists of all hints.
1558          */
1559         hstate->scan_hints = (ScanMethodHint **) hstate->all_hints;
1560         hstate->join_hints = (JoinMethodHint **) (hstate->scan_hints +
1561                 hstate->num_hints[HINT_TYPE_SCAN_METHOD]);
1562         hstate->leading_hint = (LeadingHint **) (hstate->join_hints +
1563                 hstate->num_hints[HINT_TYPE_JOIN_METHOD]);
1564         hstate->set_hints = (SetHint **) (hstate->leading_hint +
1565                 hstate->num_hints[HINT_TYPE_LEADING]);
1566
1567         return hstate;
1568 }
1569
1570 /*
1571  * Parse inside of parentheses of scan-method hints.
1572  */
1573 static const char *
1574 ScanMethodHintParse(ScanMethodHint *hint, HintState *hstate, Query *parse,
1575                                         const char *str)
1576 {
1577         const char         *keyword = hint->base.keyword;
1578         HintKeyword             hint_keyword = hint->base.hint_keyword;
1579         List               *name_list = NIL;
1580         int                             length;
1581
1582         if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1583                 return NULL;
1584
1585         /* Parse relation name and index name(s) if given hint accepts. */
1586         length = list_length(name_list);
1587         if (length > 0)
1588         {
1589                 hint->relname = linitial(name_list);
1590                 hint->indexnames = list_delete_first(name_list);
1591
1592                 /* check whether the hint accepts index name(s). */
1593                 if (length != 1 &&
1594                         hint_keyword != HINT_KEYWORD_INDEXSCAN &&
1595                         hint_keyword != HINT_KEYWORD_INDEXSCANREGEXP &&
1596 #if PG_VERSION_NUM >= 90200
1597                         hint_keyword != HINT_KEYWORD_INDEXONLYSCAN &&
1598                         hint_keyword != HINT_KEYWORD_INDEXONLYSCANREGEXP &&
1599 #endif
1600                         hint_keyword != HINT_KEYWORD_BITMAPSCAN &&
1601                         hint_keyword != HINT_KEYWORD_BITMAPSCANREGEXP)
1602                 {
1603                         hint_ereport(str,
1604                                                  ("%s hint accepts only one relation.",
1605                                                   hint->base.keyword));
1606                         hint->base.state = HINT_STATE_ERROR;
1607                         return str;
1608                 }
1609         }
1610         else
1611         {
1612                 hint_ereport(str,
1613                                          ("%s hint requires a relation.",
1614                                           hint->base.keyword));
1615                 hint->base.state = HINT_STATE_ERROR;
1616                 return str;
1617         }
1618
1619         /* Set a bit for specified hint. */
1620         switch (hint_keyword)
1621         {
1622                 case HINT_KEYWORD_SEQSCAN:
1623                         hint->enforce_mask = ENABLE_SEQSCAN;
1624                         break;
1625                 case HINT_KEYWORD_INDEXSCAN:
1626                         hint->enforce_mask = ENABLE_INDEXSCAN;
1627                         break;
1628                 case HINT_KEYWORD_INDEXSCANREGEXP:
1629                         hint->enforce_mask = ENABLE_INDEXSCAN;
1630                         hint->regexp = true;
1631                         break;
1632                 case HINT_KEYWORD_BITMAPSCAN:
1633                         hint->enforce_mask = ENABLE_BITMAPSCAN;
1634                         break;
1635                 case HINT_KEYWORD_BITMAPSCANREGEXP:
1636                         hint->enforce_mask = ENABLE_BITMAPSCAN;
1637                         hint->regexp = true;
1638                         break;
1639                 case HINT_KEYWORD_TIDSCAN:
1640                         hint->enforce_mask = ENABLE_TIDSCAN;
1641                         break;
1642                 case HINT_KEYWORD_NOSEQSCAN:
1643                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
1644                         break;
1645                 case HINT_KEYWORD_NOINDEXSCAN:
1646                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
1647                         break;
1648                 case HINT_KEYWORD_NOBITMAPSCAN:
1649                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
1650                         break;
1651                 case HINT_KEYWORD_NOTIDSCAN:
1652                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
1653                         break;
1654 #if PG_VERSION_NUM >= 90200
1655                 case HINT_KEYWORD_INDEXONLYSCAN:
1656                         hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1657                         break;
1658                 case HINT_KEYWORD_INDEXONLYSCANREGEXP:
1659                         hint->enforce_mask = ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN;
1660                         hint->regexp = true;
1661                         break;
1662                 case HINT_KEYWORD_NOINDEXONLYSCAN:
1663                         hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXONLYSCAN;
1664                         break;
1665 #endif
1666                 default:
1667                         hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1668                         return NULL;
1669                         break;
1670         }
1671
1672         return str;
1673 }
1674
1675 static const char *
1676 JoinMethodHintParse(JoinMethodHint *hint, HintState *hstate, Query *parse,
1677                                         const char *str)
1678 {
1679         const char         *keyword = hint->base.keyword;
1680         HintKeyword             hint_keyword = hint->base.hint_keyword;
1681         List               *name_list = NIL;
1682
1683         if ((str = parse_parentheses(str, &name_list, hint_keyword)) == NULL)
1684                 return NULL;
1685
1686         hint->nrels = list_length(name_list);
1687
1688         if (hint->nrels > 0)
1689         {
1690                 ListCell   *l;
1691                 int                     i = 0;
1692
1693                 /*
1694                  * Transform relation names from list to array to sort them with qsort
1695                  * after.
1696                  */
1697                 hint->relnames = palloc(sizeof(char *) * hint->nrels);
1698                 foreach (l, name_list)
1699                 {
1700                         hint->relnames[i] = lfirst(l);
1701                         i++;
1702                 }
1703         }
1704
1705         list_free(name_list);
1706
1707         /* A join hint requires at least two relations */
1708         if (hint->nrels < 2)
1709         {
1710                 hint_ereport(str,
1711                                          ("%s hint requires at least two relations.",
1712                                           hint->base.keyword));
1713                 hint->base.state = HINT_STATE_ERROR;
1714                 return str;
1715         }
1716
1717         /* Sort hints in alphabetical order of relation names. */
1718         qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
1719
1720         switch (hint_keyword)
1721         {
1722                 case HINT_KEYWORD_NESTLOOP:
1723                         hint->enforce_mask = ENABLE_NESTLOOP;
1724                         break;
1725                 case HINT_KEYWORD_MERGEJOIN:
1726                         hint->enforce_mask = ENABLE_MERGEJOIN;
1727                         break;
1728                 case HINT_KEYWORD_HASHJOIN:
1729                         hint->enforce_mask = ENABLE_HASHJOIN;
1730                         break;
1731                 case HINT_KEYWORD_NONESTLOOP:
1732                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
1733                         break;
1734                 case HINT_KEYWORD_NOMERGEJOIN:
1735                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
1736                         break;
1737                 case HINT_KEYWORD_NOHASHJOIN:
1738                         hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
1739                         break;
1740                 default:
1741                         hint_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
1742                         return NULL;
1743                         break;
1744         }
1745
1746         return str;
1747 }
1748
1749 static bool
1750 OuterInnerPairCheck(OuterInnerRels *outer_inner)
1751 {
1752         ListCell *l;
1753         if (outer_inner->outer_inner_pair == NIL)
1754         {
1755                 if (outer_inner->relation)
1756                         return true;
1757                 else
1758                         return false;
1759         }
1760
1761         if (list_length(outer_inner->outer_inner_pair) == 2)
1762         {
1763                 foreach(l, outer_inner->outer_inner_pair)
1764                 {
1765                         if (!OuterInnerPairCheck(lfirst(l)))
1766                                 return false;
1767                 }
1768         }
1769         else
1770                 return false;
1771
1772         return true;
1773 }
1774
1775 static List *
1776 OuterInnerList(OuterInnerRels *outer_inner)
1777 {
1778         List               *outer_inner_list = NIL;
1779         ListCell           *l;
1780         OuterInnerRels *outer_inner_rels;
1781
1782         foreach(l, outer_inner->outer_inner_pair)
1783         {
1784                 outer_inner_rels = (OuterInnerRels *)(lfirst(l));
1785
1786                 if (outer_inner_rels->relation != NULL)
1787                         outer_inner_list = lappend(outer_inner_list,
1788                                                                            outer_inner_rels->relation);
1789                 else
1790                         outer_inner_list = list_concat(outer_inner_list,
1791                                                                                    OuterInnerList(outer_inner_rels));
1792         }
1793         return outer_inner_list;
1794 }
1795
1796 static const char *
1797 LeadingHintParse(LeadingHint *hint, HintState *hstate, Query *parse,
1798                                  const char *str)
1799 {
1800         List               *name_list = NIL;
1801         OuterInnerRels *outer_inner = NULL;
1802
1803         if ((str = parse_parentheses_Leading(str, &name_list, &outer_inner)) ==
1804                 NULL)
1805                 return NULL;
1806
1807         if (outer_inner != NULL)
1808                 name_list = OuterInnerList(outer_inner);
1809
1810         hint->relations = name_list;
1811         hint->outer_inner = outer_inner;
1812
1813         /* A Leading hint requires at least two relations */
1814         if ( hint->outer_inner == NULL && list_length(hint->relations) < 2)
1815         {
1816                 hint_ereport(hint->base.hint_str,
1817                                          ("%s hint requires at least two relations.",
1818                                           HINT_LEADING));
1819                 hint->base.state = HINT_STATE_ERROR;
1820         }
1821         else if (hint->outer_inner != NULL &&
1822                          !OuterInnerPairCheck(hint->outer_inner))
1823         {
1824                 hint_ereport(hint->base.hint_str,
1825                                          ("%s hint requires two sets of relations when parentheses nests.",
1826                                           HINT_LEADING));
1827                 hint->base.state = HINT_STATE_ERROR;
1828         }
1829
1830         return str;
1831 }
1832
1833 static const char *
1834 SetHintParse(SetHint *hint, HintState *hstate, Query *parse, const char *str)
1835 {
1836         List   *name_list = NIL;
1837
1838         if ((str = parse_parentheses(str, &name_list, hint->base.hint_keyword))
1839                 == NULL)
1840                 return NULL;
1841
1842         hint->words = name_list;
1843
1844         /* We need both name and value to set GUC parameter. */
1845         if (list_length(name_list) == 2)
1846         {
1847                 hint->name = linitial(name_list);
1848                 hint->value = lsecond(name_list);
1849         }
1850         else
1851         {
1852                 hint_ereport(hint->base.hint_str,
1853                                          ("%s hint requires name and value of GUC parameter.",
1854                                           HINT_SET));
1855                 hint->base.state = HINT_STATE_ERROR;
1856         }
1857
1858         return str;
1859 }
1860
1861 /*
1862  * set GUC parameter functions
1863  */
1864
1865 static int
1866 set_config_option_wrapper(const char *name, const char *value,
1867                                                   GucContext context, GucSource source,
1868                                                   GucAction action, bool changeVal, int elevel)
1869 {
1870         int                             result = 0;
1871         MemoryContext   ccxt = CurrentMemoryContext;
1872
1873         PG_TRY();
1874         {
1875 #if PG_VERSION_NUM >= 90200
1876                 result = set_config_option(name, value, context, source,
1877                                                                    action, changeVal, 0);
1878 #else
1879                 result = set_config_option(name, value, context, source,
1880                                                                    action, changeVal);
1881 #endif
1882         }
1883         PG_CATCH();
1884         {
1885                 ErrorData          *errdata;
1886
1887                 /* Save error info */
1888                 MemoryContextSwitchTo(ccxt);
1889                 errdata = CopyErrorData();
1890                 FlushErrorState();
1891
1892                 ereport(elevel, (errcode(errdata->sqlerrcode),
1893                                 errmsg("%s", errdata->message),
1894                                 errdata->detail ? errdetail("%s", errdata->detail) : 0,
1895                                 errdata->hint ? errhint("%s", errdata->hint) : 0));
1896                 FreeErrorData(errdata);
1897         }
1898         PG_END_TRY();
1899
1900         return result;
1901 }
1902
1903 static int
1904 set_config_options(SetHint **options, int noptions, GucContext context)
1905 {
1906         int     i;
1907         int     save_nestlevel;
1908
1909         save_nestlevel = NewGUCNestLevel();
1910
1911         for (i = 0; i < noptions; i++)
1912         {
1913                 SetHint    *hint = options[i];
1914                 int                     result;
1915
1916                 if (!hint_state_enabled(hint))
1917                         continue;
1918
1919                 result = set_config_option_wrapper(hint->name, hint->value, context,
1920                                                                                    PGC_S_SESSION, GUC_ACTION_SAVE, true,
1921                                                                                    pg_hint_plan_parse_messages);
1922                 if (result != 0)
1923                         hint->base.state = HINT_STATE_USED;
1924                 else
1925                         hint->base.state = HINT_STATE_ERROR;
1926         }
1927
1928         return save_nestlevel;
1929 }
1930
1931 #define SET_CONFIG_OPTION(name, type_bits) \
1932         set_config_option_wrapper((name), \
1933                 (mask & (type_bits)) ? "true" : "false", \
1934                 context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
1935
1936 static void
1937 set_scan_config_options(unsigned char enforce_mask, GucContext context)
1938 {
1939         unsigned char   mask;
1940
1941         if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
1942                 enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
1943 #if PG_VERSION_NUM >= 90200
1944                 || enforce_mask == (ENABLE_INDEXSCAN | ENABLE_INDEXONLYSCAN)
1945 #endif
1946                 )
1947                 mask = enforce_mask;
1948         else
1949                 mask = enforce_mask & current_hint->init_scan_mask;
1950
1951         SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
1952         SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
1953         SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
1954         SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
1955 #if PG_VERSION_NUM >= 90200
1956         SET_CONFIG_OPTION("enable_indexonlyscan", ENABLE_INDEXONLYSCAN);
1957 #endif
1958 }
1959
1960 static void
1961 set_join_config_options(unsigned char enforce_mask, GucContext context)
1962 {
1963         unsigned char   mask;
1964
1965         if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
1966                 enforce_mask == ENABLE_HASHJOIN)
1967                 mask = enforce_mask;
1968         else
1969                 mask = enforce_mask & current_hint->init_join_mask;
1970
1971         SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
1972         SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
1973         SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
1974 }
1975
1976 /*
1977  * pg_hint_plan hook functions
1978  */
1979
1980 static void
1981 pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
1982                                                         ParamListInfo params, bool isTopLevel,
1983                                                         DestReceiver *dest, char *completionTag)
1984 {
1985         Node                               *node;
1986
1987         if (!pg_hint_plan_enable_hint)
1988         {
1989                 if (prev_ProcessUtility)
1990                         (*prev_ProcessUtility) (parsetree, queryString, params,
1991                                                                         isTopLevel, dest, completionTag);
1992                 else
1993                         standard_ProcessUtility(parsetree, queryString, params,
1994                                                                         isTopLevel, dest, completionTag);
1995
1996                 return;
1997         }
1998
1999         node = parsetree;
2000         if (IsA(node, ExplainStmt))
2001         {
2002                 /*
2003                  * Draw out parse tree of actual query from Query struct of EXPLAIN
2004                  * statement.
2005                  */
2006                 ExplainStmt        *stmt;
2007                 Query              *query;
2008
2009                 stmt = (ExplainStmt *) node;
2010
2011                 Assert(IsA(stmt->query, Query));
2012                 query = (Query *) stmt->query;
2013
2014                 if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
2015                         node = query->utilityStmt;
2016         }
2017
2018         /*
2019          * If the query was a EXECUTE or CREATE TABLE AS EXECUTE, get query string
2020          * specified to preceding PREPARE command to use it as source of hints.
2021          */
2022         if (IsA(node, ExecuteStmt))
2023         {
2024                 ExecuteStmt        *stmt;
2025
2026                 stmt = (ExecuteStmt *) node;
2027                 stmt_name = stmt->name;
2028         }
2029 #if PG_VERSION_NUM >= 90200
2030         /*
2031          * CREATE AS EXECUTE behavior has changed since 9.2, so we must handle it
2032          * specially here.
2033          */
2034         if (IsA(node, CreateTableAsStmt))
2035         {
2036                 CreateTableAsStmt          *stmt;
2037                 Query              *query;
2038
2039                 stmt = (CreateTableAsStmt *) node;
2040                 Assert(IsA(stmt->query, Query));
2041                 query = (Query *) stmt->query;
2042
2043                 if (query->commandType == CMD_UTILITY &&
2044                         IsA(query->utilityStmt, ExecuteStmt))
2045                 {
2046                         ExecuteStmt *estmt = (ExecuteStmt *) query->utilityStmt;
2047                         stmt_name = estmt->name;
2048                 }
2049         }
2050 #endif
2051         if (stmt_name)
2052         {
2053                 PG_TRY();
2054                 {
2055                         if (prev_ProcessUtility)
2056                                 (*prev_ProcessUtility) (parsetree, queryString, params,
2057                                                                                 isTopLevel, dest, completionTag);
2058                         else
2059                                 standard_ProcessUtility(parsetree, queryString, params,
2060                                                                                 isTopLevel, dest, completionTag);
2061                 }
2062                 PG_CATCH();
2063                 {
2064                         stmt_name = NULL;
2065                         PG_RE_THROW();
2066                 }
2067                 PG_END_TRY();
2068
2069                 stmt_name = NULL;
2070
2071                 return;
2072         }
2073
2074         if (prev_ProcessUtility)
2075                 (*prev_ProcessUtility) (parsetree, queryString, params,
2076                                                                 isTopLevel, dest, completionTag);
2077         else
2078                 standard_ProcessUtility(parsetree, queryString, params,
2079                                                                 isTopLevel, dest, completionTag);
2080 }
2081
2082 /*
2083  * Push a hint into hint stack which is implemented with List struct.  Head of
2084  * list is top of stack.
2085  */
2086 static void
2087 push_hint(HintState *hstate)
2088 {
2089         /* Prepend new hint to the list means pushing to stack. */
2090         HintStateStack = lcons(hstate, HintStateStack);
2091
2092         /* Pushed hint is the one which should be used hereafter. */
2093         current_hint = hstate;
2094 }
2095
2096 /* Pop a hint from hint stack.  Popped hint is automatically discarded. */
2097 static void
2098 pop_hint(void)
2099 {
2100         /* Hint stack must not be empty. */
2101         if(HintStateStack == NIL)
2102                 elog(ERROR, "hint stack is empty");
2103
2104         /*
2105          * Take a hint at the head from the list, and free it.  Switch current_hint
2106          * to point new head (NULL if the list is empty).
2107          */
2108         HintStateStack = list_delete_first(HintStateStack);
2109         HintStateDelete(current_hint);
2110         if(HintStateStack == NIL)
2111                 current_hint = NULL;
2112         else
2113                 current_hint = (HintState *) lfirst(list_head(HintStateStack));
2114 }
2115
2116 static PlannedStmt *
2117 pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
2118 {
2119         const char         *hints;
2120         const char         *query;
2121         int                             save_nestlevel;
2122         PlannedStmt        *result;
2123         HintState          *hstate;
2124
2125         /*
2126          * Use standard planner if pg_hint_plan is disabled.  Other hook functions
2127          * try to change plan with current_hint if any, so set it to NULL.
2128          */
2129         if (!pg_hint_plan_enable_hint)
2130                 goto standard_planner_proc;
2131
2132         /* Create hint struct from client-supplied query string. */
2133         query = get_query_string();
2134
2135         /*
2136          * get_hints_from_table
2137          * TODO: replace "app1" with current application_name setting of the
2138          * session.
2139          * XXX: use something instead of debug_query_string?
2140          */
2141         hints = get_hints_from_table(query, application_name);
2142         elog(DEBUG1,
2143                  "pg_hint_plan: get_hints_from_table [%s][%s]=>[%s]",
2144                  query, application_name,
2145                  hints ? hints : "(none)");
2146         if (hints == NULL)
2147                 hints = get_hints_from_comment(query);
2148         hstate = create_hintstate(parse, hints);
2149
2150         /*
2151          * Use standard planner if the statement has not valid hint.  Other hook
2152          * functions try to change plan with current_hint if any, so set it to
2153          * NULL.
2154          */
2155         if (!hstate)
2156                 goto standard_planner_proc;
2157
2158         /*
2159          * Push new hint struct to the hint stack to disable previous hint context.
2160          */
2161         push_hint(hstate);
2162
2163         /* Set GUC parameters which are specified with Set hint. */
2164         save_nestlevel = set_config_options(current_hint->set_hints,
2165                                                                                 current_hint->num_hints[HINT_TYPE_SET],
2166                                                                                 current_hint->context);
2167
2168         if (enable_seqscan)
2169                 current_hint->init_scan_mask |= ENABLE_SEQSCAN;
2170         if (enable_indexscan)
2171                 current_hint->init_scan_mask |= ENABLE_INDEXSCAN;
2172         if (enable_bitmapscan)
2173                 current_hint->init_scan_mask |= ENABLE_BITMAPSCAN;
2174         if (enable_tidscan)
2175                 current_hint->init_scan_mask |= ENABLE_TIDSCAN;
2176 #if PG_VERSION_NUM >= 90200
2177         if (enable_indexonlyscan)
2178                 current_hint->init_scan_mask |= ENABLE_INDEXONLYSCAN;
2179 #endif
2180         if (enable_nestloop)
2181                 current_hint->init_join_mask |= ENABLE_NESTLOOP;
2182         if (enable_mergejoin)
2183                 current_hint->init_join_mask |= ENABLE_MERGEJOIN;
2184         if (enable_hashjoin)
2185                 current_hint->init_join_mask |= ENABLE_HASHJOIN;
2186
2187         /*
2188          * Use PG_TRY mechanism to recover GUC parameters and current_hint to the
2189          * state when this planner started when error occurred in planner.
2190          */
2191         PG_TRY();
2192         {
2193                 if (prev_planner)
2194                         result = (*prev_planner) (parse, cursorOptions, boundParams);
2195                 else
2196                         result = standard_planner(parse, cursorOptions, boundParams);
2197         }
2198         PG_CATCH();
2199         {
2200                 /*
2201                  * Rollback changes of GUC parameters, and pop current hint context
2202                  * from hint stack to rewind the state.
2203                  */
2204                 AtEOXact_GUC(true, save_nestlevel);
2205                 pop_hint();
2206                 PG_RE_THROW();
2207         }
2208         PG_END_TRY();
2209
2210         /* Print hint in debug mode. */
2211         if (pg_hint_plan_debug_print)
2212                 HintStateDump(current_hint);
2213
2214         /*
2215          * Rollback changes of GUC parameters, and pop current hint context from
2216          * hint stack to rewind the state.
2217          */
2218         AtEOXact_GUC(true, save_nestlevel);
2219         pop_hint();
2220
2221         return result;
2222
2223 standard_planner_proc:
2224         current_hint = NULL;
2225         if (prev_planner)
2226                 return (*prev_planner) (parse, cursorOptions, boundParams);
2227         else
2228                 return standard_planner(parse, cursorOptions, boundParams);
2229 }
2230
2231 /*
2232  * Return scan method hint which matches given aliasname.
2233  */
2234 static ScanMethodHint *
2235 find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
2236 {
2237         RangeTblEntry  *rte;
2238         int                             i;
2239
2240         /*
2241          * We can't apply scan method hint if the relation is:
2242          *   - not a base relation
2243          *   - not an ordinary relation (such as join and subquery)
2244          */
2245         if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
2246                 return NULL;
2247
2248         rte = root->simple_rte_array[rel->relid];
2249
2250         /* We can't force scan method of foreign tables */
2251         if (rte->relkind == RELKIND_FOREIGN_TABLE)
2252                 return NULL;
2253
2254         /* Find scan method hint, which matches given names, from the list. */
2255         for (i = 0; i < current_hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
2256         {
2257                 ScanMethodHint *hint = current_hint->scan_hints[i];
2258
2259                 /* We ignore disabled hints. */
2260                 if (!hint_state_enabled(hint))
2261                         continue;
2262
2263                 if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
2264                         return hint;
2265         }
2266
2267         return NULL;
2268 }
2269
2270 /*
2271  * regexeq
2272  *
2273  * Returns TRUE on match, FALSE on no match.
2274  *
2275  *   s1 --- the data to match against
2276  *   s2 --- the pattern
2277  *
2278  * Because we copy s1 to NameData, make the size of s1 less than NAMEDATALEN.
2279  */
2280 static bool
2281 regexpeq(const char *s1, const char *s2)
2282 {
2283         NameData        name;
2284         text       *regexp;
2285         Datum           result;
2286
2287         strcpy(name.data, s1);
2288         regexp = cstring_to_text(s2);
2289
2290         result = DirectFunctionCall2Coll(nameregexeq,
2291                                                                          DEFAULT_COLLATION_OID,
2292                                                                          NameGetDatum(&name),
2293                                                                          PointerGetDatum(regexp));
2294         return DatumGetBool(result);
2295 }
2296
2297 static void
2298 delete_indexes(ScanMethodHint *hint, RelOptInfo *rel, Oid relationObjectId)
2299 {
2300         ListCell           *cell;
2301         ListCell           *prev;
2302         ListCell           *next;
2303         StringInfoData  buf;
2304
2305         /*
2306          * We delete all the IndexOptInfo list and prevent you from being usable by
2307          * a scan.
2308          */
2309         if (hint->enforce_mask == ENABLE_SEQSCAN ||
2310                 hint->enforce_mask == ENABLE_TIDSCAN)
2311         {
2312                 list_free_deep(rel->indexlist);
2313                 rel->indexlist = NIL;
2314                 hint->base.state = HINT_STATE_USED;
2315
2316                 return;
2317         }
2318
2319         /*
2320          * When a list of indexes is not specified, we just use all indexes.
2321          */
2322         if (hint->indexnames == NIL)
2323                 return;
2324
2325         /*
2326          * Leaving only an specified index, we delete it from a IndexOptInfo list
2327          * other than it.
2328          */
2329         prev = NULL;
2330         if (pg_hint_plan_debug_print)
2331                 initStringInfo(&buf);
2332
2333         for (cell = list_head(rel->indexlist); cell; cell = next)
2334         {
2335                 IndexOptInfo   *info = (IndexOptInfo *) lfirst(cell);
2336                 char               *indexname = get_rel_name(info->indexoid);
2337                 ListCell           *l;
2338                 bool                    use_index = false;
2339
2340                 next = lnext(cell);
2341
2342                 foreach(l, hint->indexnames)
2343                 {
2344                         char   *hintname = (char *) lfirst(l);
2345                         bool    result;
2346
2347                         if (hint->regexp)
2348                                 result = regexpeq(indexname, hintname);
2349                         else
2350                                 result = RelnameCmp(&indexname, &hintname) == 0;
2351
2352                         if (result)
2353                         {
2354                                 use_index = true;
2355                                 if (pg_hint_plan_debug_print)
2356                                 {
2357                                         appendStringInfoCharMacro(&buf, ' ');
2358                                         quote_value(&buf, indexname);
2359                                 }
2360
2361                                 break;
2362                         }
2363                 }
2364
2365                 /*
2366                  * to make the index a candidate when definition of this index is
2367                  * matched with the index's definition of current_hint.
2368                  */
2369                 if (OidIsValid(relationObjectId) && !use_index)
2370                 {
2371                         foreach(l, current_hint->parent_index_infos)
2372                         {
2373                                 int                                     i;
2374                                 HeapTuple                       ht_idx;
2375                                 ParentIndexInfo    *p_info = (ParentIndexInfo *)lfirst(l);
2376
2377                                 /* check to match the parameter of unique */
2378                                 if (p_info->indisunique != info->unique)
2379                                         continue;
2380
2381                                 /* check to match the parameter of index's method */
2382                                 if (p_info->method != info->relam)
2383                                         continue;
2384
2385                                 /* to check to match the indexkey's configuration */
2386                                 if ((list_length(p_info->column_names)) !=
2387                                          info->ncolumns)
2388                                         continue;
2389
2390                                 /* check to match the indexkey's configuration */
2391                                 for (i = 0; i < info->ncolumns; i++)
2392                                 {
2393                                         char       *c_attname = NULL;
2394                                         char       *p_attname = NULL;
2395
2396                                         p_attname =
2397                                                 list_nth(p_info->column_names, i);
2398
2399                                         /* both are expressions */
2400                                         if (info->indexkeys[i] == 0 && !p_attname)
2401                                                 continue;
2402
2403                                         /* one's column is expression, the other is not */
2404                                         if (info->indexkeys[i] == 0 || !p_attname)
2405                                                 break;
2406
2407                                         c_attname = get_attname(relationObjectId,
2408                                                                                                 info->indexkeys[i]);
2409
2410                                         if (strcmp(p_attname, c_attname) != 0)
2411                                                 break;
2412
2413                                         if (p_info->indcollation[i] != info->indexcollations[i])
2414                                                 break;
2415
2416                                         if (p_info->opclass[i] != info->opcintype[i])
2417                                                 break;
2418
2419                                         if (((p_info->indoption[i] & INDOPTION_DESC) != 0) !=
2420                                                 info->reverse_sort[i])
2421                                                 break;
2422
2423                                         if (((p_info->indoption[i] & INDOPTION_NULLS_FIRST) != 0) !=
2424                                                 info->nulls_first[i])
2425                                                 break;
2426
2427                                 }
2428
2429                                 if (i != info->ncolumns)
2430                                         continue;
2431
2432                                 if ((p_info->expression_str && (info->indexprs != NIL)) ||
2433                                         (p_info->indpred_str && (info->indpred != NIL)))
2434                                 {
2435                                         /*
2436                                          * Fetch the pg_index tuple by the Oid of the index
2437                                          */
2438                                         ht_idx = SearchSysCache1(INDEXRELID,
2439                                                                                          ObjectIdGetDatum(info->indexoid));
2440
2441                                         /* check to match the expression's parameter of index */
2442                                         if (p_info->expression_str &&
2443                                                 !heap_attisnull(ht_idx, Anum_pg_index_indexprs))
2444                                         {
2445                                                 Datum       exprsDatum;
2446                                                 bool        isnull;
2447                                                 Datum       result;
2448
2449                                                 /*
2450                                                  * to change the expression's parameter of child's
2451                                                  * index to strings
2452                                                  */
2453                                                 exprsDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2454                                                                                                          Anum_pg_index_indexprs,
2455                                                                                                          &isnull);
2456
2457                                                 result = DirectFunctionCall2(pg_get_expr,
2458                                                                                                          exprsDatum,
2459                                                                                                          ObjectIdGetDatum(
2460                                                                                                                  relationObjectId));
2461
2462                                                 if (strcmp(p_info->expression_str,
2463                                                                    text_to_cstring(DatumGetTextP(result))) != 0)
2464                                                 {
2465                                                         /* Clean up */
2466                                                         ReleaseSysCache(ht_idx);
2467
2468                                                         continue;
2469                                                 }
2470                                         }
2471
2472                                         /* Check to match the predicate's paraameter of index */
2473                                         if (p_info->indpred_str &&
2474                                                 !heap_attisnull(ht_idx, Anum_pg_index_indpred))
2475                                         {
2476                                                 Datum       predDatum;
2477                                                 bool        isnull;
2478                                                 Datum       result;
2479
2480                                                 /*
2481                                                  * to change the predicate's parabeter of child's
2482                                                  * index to strings
2483                                                  */
2484                                                 predDatum = SysCacheGetAttr(INDEXRELID, ht_idx,
2485                                                                                                          Anum_pg_index_indpred,
2486                                                                                                          &isnull);
2487
2488                                                 result = DirectFunctionCall2(pg_get_expr,
2489                                                                                                          predDatum,
2490                                                                                                          ObjectIdGetDatum(
2491                                                                                                                  relationObjectId));
2492
2493                                                 if (strcmp(p_info->indpred_str,
2494                                                                    text_to_cstring(DatumGetTextP(result))) != 0)
2495                                                 {
2496                                                         /* Clean up */
2497                                                         ReleaseSysCache(ht_idx);
2498
2499                                                         continue;
2500                                                 }
2501                                         }
2502
2503                                         /* Clean up */
2504                                         ReleaseSysCache(ht_idx);
2505                                 }
2506                                 else if (p_info->expression_str || (info->indexprs != NIL))
2507                                         continue;
2508                                 else if (p_info->indpred_str || (info->indpred != NIL))
2509                                         continue;
2510
2511                                 use_index = true;
2512
2513                                 /* to log the candidate of index */
2514                                 if (pg_hint_plan_debug_print)
2515                                 {
2516                                         appendStringInfoCharMacro(&buf, ' ');
2517                                         quote_value(&buf, indexname);
2518                                 }
2519
2520                                 break;
2521                         }
2522                 }
2523
2524                 if (!use_index)
2525                         rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
2526                 else
2527                         prev = cell;
2528
2529                 pfree(indexname);
2530         }
2531
2532         if (pg_hint_plan_debug_print)
2533         {
2534                 char   *relname;
2535                 StringInfoData  rel_buf;
2536
2537                 if (OidIsValid(relationObjectId))
2538                         relname = get_rel_name(relationObjectId);
2539                 else
2540                         relname = hint->relname;
2541
2542                 initStringInfo(&rel_buf);
2543                 quote_value(&rel_buf, relname);
2544
2545                 ereport(LOG,
2546                                 (errmsg("available indexes for %s(%s):%s",
2547                                          hint->base.keyword,
2548                                          rel_buf.data,
2549                                          buf.data)));
2550                 pfree(buf.data);
2551                 pfree(rel_buf.data);
2552         }
2553 }
2554
2555 /* 
2556  * Return information of index definition.
2557  */
2558 static ParentIndexInfo *
2559 get_parent_index_info(Oid indexoid, Oid relid)
2560 {
2561         ParentIndexInfo *p_info = palloc(sizeof(ParentIndexInfo));
2562         Relation            indexRelation;
2563         Form_pg_index   index;
2564         char               *attname;
2565         int                             i;
2566
2567         indexRelation = index_open(indexoid, RowExclusiveLock);
2568
2569         index = indexRelation->rd_index;
2570
2571         p_info->indisunique = index->indisunique;
2572         p_info->method = indexRelation->rd_rel->relam;
2573
2574         p_info->column_names = NIL;
2575         p_info->indcollation = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2576         p_info->opclass = (Oid *) palloc(sizeof(Oid) * index->indnatts);
2577         p_info->indoption = (int16 *) palloc(sizeof(Oid) * index->indnatts);
2578
2579         for (i = 0; i < index->indnatts; i++)
2580         {
2581                 attname = get_attname(relid, index->indkey.values[i]);
2582                 p_info->column_names = lappend(p_info->column_names, attname);
2583
2584                 p_info->indcollation[i] = indexRelation->rd_indcollation[i];
2585                 p_info->opclass[i] = indexRelation->rd_opcintype[i];
2586                 p_info->indoption[i] = indexRelation->rd_indoption[i];
2587         }
2588
2589         /*
2590          * to check to match the expression's paraameter of index with child indexes
2591          */
2592         p_info->expression_str = NULL;
2593         if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indexprs))
2594         {
2595                 Datum       exprsDatum;
2596                 bool            isnull;
2597                 Datum           result;
2598
2599                 exprsDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2600                                                                          Anum_pg_index_indexprs, &isnull);
2601
2602                 result = DirectFunctionCall2(pg_get_expr,
2603                                                                          exprsDatum,
2604                                                                          ObjectIdGetDatum(relid));
2605
2606                 p_info->expression_str = text_to_cstring(DatumGetTextP(result));
2607         }
2608
2609         /*
2610          * to check to match the predicate's paraameter of index with child indexes
2611          */
2612         p_info->indpred_str = NULL;
2613         if(!heap_attisnull(indexRelation->rd_indextuple, Anum_pg_index_indpred))
2614         {
2615                 Datum       predDatum;
2616                 bool            isnull;
2617                 Datum           result;
2618
2619                 predDatum = SysCacheGetAttr(INDEXRELID, indexRelation->rd_indextuple,
2620                                                                          Anum_pg_index_indpred, &isnull);
2621
2622                 result = DirectFunctionCall2(pg_get_expr,
2623                                                                          predDatum,
2624                                                                          ObjectIdGetDatum(relid));
2625
2626                 p_info->indpred_str = text_to_cstring(DatumGetTextP(result));
2627         }
2628
2629         index_close(indexRelation, NoLock);
2630
2631         return p_info;
2632 }
2633
2634 static void
2635 pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
2636                                                            bool inhparent, RelOptInfo *rel)
2637 {
2638         ScanMethodHint *hint;
2639
2640         if (prev_get_relation_info)
2641                 (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
2642
2643         /* Do nothing if we don't have valid hint in this context. */
2644         if (!current_hint)
2645                 return;
2646
2647         if (inhparent)
2648         {
2649                 /* store does relids of parent table. */
2650                 current_hint->parent_relid = rel->relid;
2651                 current_hint->parent_rel_oid = relationObjectId;
2652         }
2653         else if (current_hint->parent_relid != 0)
2654         {
2655                 /*
2656                  * We use the same GUC parameter if this table is the child table of a
2657                  * table called pg_hint_plan_get_relation_info just before that.
2658                  */
2659                 ListCell   *l;
2660
2661                 /* append_rel_list contains all append rels; ignore others */
2662                 foreach(l, root->append_rel_list)
2663                 {
2664                         AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
2665
2666                         /* This rel is child table. */
2667                         if (appinfo->parent_relid == current_hint->parent_relid &&
2668                                 appinfo->child_relid == rel->relid)
2669                         {
2670                                 if (current_hint->parent_hint)
2671                                         delete_indexes(current_hint->parent_hint, rel,
2672                                                                    relationObjectId);
2673
2674                                 return;
2675                         }
2676                 }
2677
2678                 /* This rel is not inherit table. */
2679                 current_hint->parent_relid = 0;
2680                 current_hint->parent_rel_oid = InvalidOid;
2681                 current_hint->parent_hint = NULL;
2682         }
2683
2684         /*
2685          * If scan method hint was given, reset GUC parameters which control
2686          * planner behavior about choosing scan methods.
2687          */
2688         if ((hint = find_scan_hint(root, rel)) == NULL)
2689         {
2690                 set_scan_config_options(current_hint->init_scan_mask,
2691                                                                 current_hint->context);
2692                 return;
2693         }
2694         set_scan_config_options(hint->enforce_mask, current_hint->context);
2695         hint->base.state = HINT_STATE_USED;
2696
2697         if (inhparent)
2698         {
2699                 Relation    relation;
2700                 List       *indexoidlist;
2701                 ListCell   *l;
2702
2703                 current_hint->parent_hint = hint;
2704
2705                 relation = heap_open(relationObjectId, NoLock);
2706                 indexoidlist = RelationGetIndexList(relation);
2707
2708                 foreach(l, indexoidlist)
2709                 {
2710                         Oid         indexoid = lfirst_oid(l);
2711                         char       *indexname = get_rel_name(indexoid);
2712                         bool        use_index = false;
2713                         ListCell   *lc;
2714                         ParentIndexInfo *parent_index_info;
2715
2716                         foreach(lc, hint->indexnames)
2717                         {
2718                                 if (RelnameCmp(&indexname, &lfirst(lc)) == 0)
2719                                 {
2720                                         use_index = true;
2721                                         break;
2722                                 }
2723                         }
2724                         if (!use_index)
2725                                 continue;
2726
2727                         parent_index_info = get_parent_index_info(indexoid,
2728                                                                                                           relationObjectId);
2729                         current_hint->parent_index_infos =
2730                                 lappend(current_hint->parent_index_infos, parent_index_info);
2731                 }
2732                 heap_close(relation, NoLock);
2733         }
2734         else
2735                 delete_indexes(hint, rel, InvalidOid);
2736 }
2737
2738 /*
2739  * Return index of relation which matches given aliasname, or 0 if not found.
2740  * If same aliasname was used multiple times in a query, return -1.
2741  */
2742 static int
2743 find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
2744                                          const char *str)
2745 {
2746         int             i;
2747         Index   found = 0;
2748
2749         for (i = 1; i < root->simple_rel_array_size; i++)
2750         {
2751                 ListCell   *l;
2752
2753                 if (root->simple_rel_array[i] == NULL)
2754                         continue;
2755
2756                 Assert(i == root->simple_rel_array[i]->relid);
2757
2758                 if (RelnameCmp(&aliasname,
2759                                            &root->simple_rte_array[i]->eref->aliasname) != 0)
2760                         continue;
2761
2762                 foreach(l, initial_rels)
2763                 {
2764                         RelOptInfo *rel = (RelOptInfo *) lfirst(l);
2765
2766                         if (rel->reloptkind == RELOPT_BASEREL)
2767                         {
2768                                 if (rel->relid != i)
2769                                         continue;
2770                         }
2771                         else
2772                         {
2773                                 Assert(rel->reloptkind == RELOPT_JOINREL);
2774
2775                                 if (!bms_is_member(i, rel->relids))
2776                                         continue;
2777                         }
2778
2779                         if (found != 0)
2780                         {
2781                                 hint_ereport(str,
2782                                                          ("Relation name \"%s\" is ambiguous.",
2783                                                           aliasname));
2784                                 return -1;
2785                         }
2786
2787                         found = i;
2788                         break;
2789                 }
2790
2791         }
2792
2793         return found;
2794 }
2795
2796 /*
2797  * Return join hint which matches given joinrelids.
2798  */
2799 static JoinMethodHint *
2800 find_join_hint(Relids joinrelids)
2801 {
2802         List       *join_hint;
2803         ListCell   *l;
2804
2805         join_hint = current_hint->join_hint_level[bms_num_members(joinrelids)];
2806
2807         foreach(l, join_hint)
2808         {
2809                 JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
2810
2811                 if (bms_equal(joinrelids, hint->joinrelids))
2812                         return hint;
2813         }
2814
2815         return NULL;
2816 }
2817
2818 static Relids
2819 OuterInnerJoinCreate(OuterInnerRels *outer_inner, LeadingHint *leading_hint,
2820         PlannerInfo *root, List *initial_rels, HintState *hstate, int nbaserel)
2821 {
2822         OuterInnerRels *outer_rels;
2823         OuterInnerRels *inner_rels;
2824         Relids                  outer_relids;
2825         Relids                  inner_relids;
2826         Relids                  join_relids;
2827         JoinMethodHint *hint;
2828
2829         if (outer_inner->relation != NULL)
2830         {
2831                 return bms_make_singleton(
2832                                         find_relid_aliasname(root, outer_inner->relation,
2833                                                                                  initial_rels,
2834                                                                                  leading_hint->base.hint_str));
2835         }
2836
2837         outer_rels = lfirst(outer_inner->outer_inner_pair->head);
2838         inner_rels = lfirst(outer_inner->outer_inner_pair->tail);
2839
2840         outer_relids = OuterInnerJoinCreate(outer_rels,
2841                                                                                 leading_hint,
2842                                                                                 root,
2843                                                                                 initial_rels,
2844                                                                                 hstate,
2845                                                                                 nbaserel);
2846         inner_relids = OuterInnerJoinCreate(inner_rels,
2847                                                                                 leading_hint,
2848                                                                                 root,
2849                                                                                 initial_rels,
2850                                                                                 hstate,
2851                                                                                 nbaserel);
2852
2853         join_relids = bms_add_members(outer_relids, inner_relids);
2854
2855         if (bms_num_members(join_relids) > nbaserel)
2856                 return join_relids;
2857
2858         /*
2859          * If we don't have join method hint, create new one for the
2860          * join combination with all join methods are enabled.
2861          */
2862         hint = find_join_hint(join_relids);
2863         if (hint == NULL)
2864         {
2865                 /*
2866                  * Here relnames is not set, since Relids bitmap is sufficient to
2867                  * control paths of this query afterward.
2868                  */
2869                 hint = (JoinMethodHint *) JoinMethodHintCreate(
2870                                         leading_hint->base.hint_str,
2871                                         HINT_LEADING,
2872                                         HINT_KEYWORD_LEADING);
2873                 hint->base.state = HINT_STATE_USED;
2874                 hint->nrels = bms_num_members(join_relids);
2875                 hint->enforce_mask = ENABLE_ALL_JOIN;
2876                 hint->joinrelids = bms_copy(join_relids);
2877                 hint->inner_nrels = bms_num_members(inner_relids);
2878                 hint->inner_joinrelids = bms_copy(inner_relids);
2879
2880                 hstate->join_hint_level[hint->nrels] =
2881                         lappend(hstate->join_hint_level[hint->nrels], hint);
2882         }
2883         else
2884         {
2885                 hint->inner_nrels = bms_num_members(inner_relids);
2886                 hint->inner_joinrelids = bms_copy(inner_relids);
2887         }
2888
2889         return join_relids;
2890 }
2891
2892 /*
2893  * Transform join method hint into handy form.
2894  *
2895  *   - create bitmap of relids from alias names, to make it easier to check
2896  *     whether a join path matches a join method hint.
2897  *   - add join method hints which are necessary to enforce join order
2898  *     specified by Leading hint
2899  */
2900 static bool
2901 transform_join_hints(HintState *hstate, PlannerInfo *root, int nbaserel,
2902                 List *initial_rels, JoinMethodHint **join_method_hints)
2903 {
2904         int                             i;
2905         int                             relid;
2906         Relids                  joinrelids;
2907         int                             njoinrels;
2908         ListCell           *l;
2909         char               *relname;
2910         LeadingHint        *lhint = NULL;
2911
2912         /*
2913          * Create bitmap of relids from alias names for each join method hint.
2914          * Bitmaps are more handy than strings in join searching.
2915          */
2916         for (i = 0; i < hstate->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
2917         {
2918                 JoinMethodHint *hint = hstate->join_hints[i];
2919                 int     j;
2920
2921                 if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
2922                         continue;
2923
2924                 bms_free(hint->joinrelids);
2925                 hint->joinrelids = NULL;
2926                 relid = 0;
2927                 for (j = 0; j < hint->nrels; j++)
2928                 {
2929                         relname = hint->relnames[j];
2930
2931                         relid = find_relid_aliasname(root, relname, initial_rels,
2932                                                                                  hint->base.hint_str);
2933
2934                         if (relid == -1)
2935                                 hint->base.state = HINT_STATE_ERROR;
2936
2937                         if (relid <= 0)
2938                                 break;
2939
2940                         if (bms_is_member(relid, hint->joinrelids))
2941                         {
2942                                 hint_ereport(hint->base.hint_str,
2943                                                          ("Relation name \"%s\" is duplicated.", relname));
2944                                 hint->base.state = HINT_STATE_ERROR;
2945                                 break;
2946                         }
2947
2948                         hint->joinrelids = bms_add_member(hint->joinrelids, relid);
2949                 }
2950
2951                 if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
2952                         continue;
2953
2954                 hstate->join_hint_level[hint->nrels] =
2955                         lappend(hstate->join_hint_level[hint->nrels], hint);
2956         }
2957
2958         /* Do nothing if no Leading hint was supplied. */
2959         if (hstate->num_hints[HINT_TYPE_LEADING] == 0)
2960                 return false;
2961
2962         /*
2963          * Decide to use Leading hint。
2964          */
2965         for (i = 0; i < hstate->num_hints[HINT_TYPE_LEADING]; i++)
2966         {
2967                 LeadingHint        *leading_hint = (LeadingHint *)hstate->leading_hint[i];
2968                 Relids                  relids;
2969
2970                 if (leading_hint->base.state == HINT_STATE_ERROR)
2971                         continue;
2972
2973                 relid = 0;
2974                 relids = NULL;
2975
2976                 foreach(l, leading_hint->relations)
2977                 {
2978                         relname = (char *)lfirst(l);;
2979
2980                         relid = find_relid_aliasname(root, relname, initial_rels,
2981                                                                                  leading_hint->base.hint_str);
2982                         if (relid == -1)
2983                                 leading_hint->base.state = HINT_STATE_ERROR;
2984
2985                         if (relid <= 0)
2986                                 break;
2987
2988                         if (bms_is_member(relid, relids))
2989                         {
2990                                 hint_ereport(leading_hint->base.hint_str,
2991                                                          ("Relation name \"%s\" is duplicated.", relname));
2992                                 leading_hint->base.state = HINT_STATE_ERROR;
2993                                 break;
2994                         }
2995
2996                         relids = bms_add_member(relids, relid);
2997                 }
2998
2999                 if (relid <= 0 || leading_hint->base.state == HINT_STATE_ERROR)
3000                         continue;
3001
3002                 if (lhint != NULL)
3003                 {
3004                         hint_ereport(lhint->base.hint_str,
3005                                  ("Conflict %s hint.", HintTypeName[lhint->base.type]));
3006                         lhint->base.state = HINT_STATE_DUPLICATION;
3007                 }
3008                 leading_hint->base.state = HINT_STATE_USED;
3009                 lhint = leading_hint;
3010         }
3011
3012         /* check to exist Leading hint marked with 'used'. */
3013         if (lhint == NULL)
3014                 return false;
3015
3016         /*
3017          * We need join method hints which fit specified join order in every join
3018          * level.  For example, Leading(A B C) virtually requires following join
3019          * method hints, if no join method hint supplied:
3020          *   - level 1: none
3021          *   - level 2: NestLoop(A B), MergeJoin(A B), HashJoin(A B)
3022          *   - level 3: NestLoop(A B C), MergeJoin(A B C), HashJoin(A B C)
3023          *
3024          * If we already have join method hint which fits specified join order in
3025          * that join level, we leave it as-is and don't add new hints.
3026          */
3027         joinrelids = NULL;
3028         njoinrels = 0;
3029         if (lhint->outer_inner == NULL)
3030         {
3031                 foreach(l, lhint->relations)
3032                 {
3033                         JoinMethodHint *hint;
3034
3035                         relname = (char *)lfirst(l);
3036
3037                         /*
3038                          * Find relid of the relation which has given name.  If we have the
3039                          * name given in Leading hint multiple times in the join, nothing to
3040                          * do.
3041                          */
3042                         relid = find_relid_aliasname(root, relname, initial_rels,
3043                                                                                  hstate->hint_str);
3044
3045                         /* Create bitmap of relids for current join level. */
3046                         joinrelids = bms_add_member(joinrelids, relid);
3047                         njoinrels++;
3048
3049                         /* We never have join method hint for single relation. */
3050                         if (njoinrels < 2)
3051                                 continue;
3052
3053                         /*
3054                          * If we don't have join method hint, create new one for the
3055                          * join combination with all join methods are enabled.
3056                          */
3057                         hint = find_join_hint(joinrelids);
3058                         if (hint == NULL)
3059                         {
3060                                 /*
3061                                  * Here relnames is not set, since Relids bitmap is sufficient
3062                                  * to control paths of this query afterward.
3063                                  */
3064                                 hint = (JoinMethodHint *) JoinMethodHintCreate(
3065                                                                                         lhint->base.hint_str,
3066                                                                                         HINT_LEADING,
3067                                                                                         HINT_KEYWORD_LEADING);
3068                                 hint->base.state = HINT_STATE_USED;
3069                                 hint->nrels = njoinrels;
3070                                 hint->enforce_mask = ENABLE_ALL_JOIN;
3071                                 hint->joinrelids = bms_copy(joinrelids);
3072                         }
3073
3074                         join_method_hints[njoinrels] = hint;
3075
3076                         if (njoinrels >= nbaserel)
3077                                 break;
3078                 }
3079                 bms_free(joinrelids);
3080
3081                 if (njoinrels < 2)
3082                         return false;
3083
3084                 /*
3085                  * Delete all join hints which have different combination from Leading
3086                  * hint.
3087                  */
3088                 for (i = 2; i <= njoinrels; i++)
3089                 {
3090                         list_free(hstate->join_hint_level[i]);
3091
3092                         hstate->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
3093                 }
3094         }
3095         else
3096         {
3097                 joinrelids = OuterInnerJoinCreate(lhint->outer_inner,
3098                                                                                   lhint,
3099                                           root,
3100                                           initial_rels,
3101                                                                                   hstate,
3102                                                                                   nbaserel);
3103
3104                 njoinrels = bms_num_members(joinrelids);
3105                 Assert(njoinrels >= 2);
3106
3107                 /*
3108                  * Delete all join hints which have different combination from Leading
3109                  * hint.
3110                  */
3111                 for (i = 2;i <= njoinrels; i++)
3112                 {
3113                         if (hstate->join_hint_level[i] != NIL)
3114                         {
3115                                 ListCell *prev = NULL;
3116                                 ListCell *next = NULL;
3117                                 for(l = list_head(hstate->join_hint_level[i]); l; l = next)
3118                                 {
3119
3120                                         JoinMethodHint *hint = (JoinMethodHint *)lfirst(l);
3121
3122                                         next = lnext(l);
3123
3124                                         if (hint->inner_nrels == 0 &&
3125                                                 !(bms_intersect(hint->joinrelids, joinrelids) == NULL ||
3126                                                   bms_equal(bms_union(hint->joinrelids, joinrelids),
3127                                                   hint->joinrelids)))
3128                                         {
3129                                                 hstate->join_hint_level[i] =
3130                                                         list_delete_cell(hstate->join_hint_level[i], l,
3131                                                                                          prev);
3132                                         }
3133                                         else
3134                                                 prev = l;
3135                                 }
3136                         }
3137                 }
3138
3139                 bms_free(joinrelids);
3140         }
3141
3142         if (hint_state_enabled(lhint))
3143         {
3144                 set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3145                 return true;
3146         }
3147         return false;
3148 }
3149
3150 /*
3151  * set_plain_rel_pathlist
3152  *        Build access paths for a plain relation (no subquery, no inheritance)
3153  *
3154  * This function was copied and edited from set_plain_rel_pathlist() in
3155  * src/backend/optimizer/path/allpaths.c
3156  */
3157 static void
3158 set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
3159 {
3160         /* Consider sequential scan */
3161 #if PG_VERSION_NUM >= 90200
3162         add_path(rel, create_seqscan_path(root, rel, NULL));
3163 #else
3164         add_path(rel, create_seqscan_path(root, rel));
3165 #endif
3166
3167         /* Consider index scans */
3168         create_index_paths(root, rel);
3169
3170         /* Consider TID scans */
3171         create_tidscan_paths(root, rel);
3172
3173         /* Now find the cheapest of the paths for this rel */
3174         set_cheapest(rel);
3175 }
3176
3177 static void
3178 rebuild_scan_path(HintState *hstate, PlannerInfo *root, int level,
3179                                   List *initial_rels)
3180 {
3181         ListCell   *l;
3182
3183         foreach(l, initial_rels)
3184         {
3185                 RelOptInfo         *rel = (RelOptInfo *) lfirst(l);
3186                 RangeTblEntry  *rte;
3187                 ScanMethodHint *hint;
3188
3189                 /* Skip relations which we can't choose scan method. */
3190                 if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
3191                         continue;
3192
3193                 rte = root->simple_rte_array[rel->relid];
3194
3195                 /* We can't force scan method of foreign tables */
3196                 if (rte->relkind == RELKIND_FOREIGN_TABLE)
3197                         continue;
3198
3199                 /*
3200                  * Create scan paths with GUC parameters which are at the beginning of
3201                  * planner if scan method hint is not specified, otherwise use
3202                  * specified hints and mark the hint as used.
3203                  */
3204                 if ((hint = find_scan_hint(root, rel)) == NULL)
3205                         set_scan_config_options(hstate->init_scan_mask,
3206                                                                         hstate->context);
3207                 else
3208                 {
3209                         set_scan_config_options(hint->enforce_mask, hstate->context);
3210                         hint->base.state = HINT_STATE_USED;
3211                 }
3212
3213                 list_free_deep(rel->pathlist);
3214                 rel->pathlist = NIL;
3215                 if (rte->inh)
3216                 {
3217                         /* It's an "append relation", process accordingly */
3218                         set_append_rel_pathlist(root, rel, rel->relid, rte);
3219                 }
3220                 else
3221                 {
3222                         set_plain_rel_pathlist(root, rel, rte);
3223                 }
3224         }
3225
3226         /*
3227          * Restore the GUC variables we set above.
3228          */
3229         set_scan_config_options(hstate->init_scan_mask, hstate->context);
3230 }
3231
3232 /*
3233  * wrapper of make_join_rel()
3234  *
3235  * call make_join_rel() after changing enable_* parameters according to given
3236  * hints.
3237  */
3238 static RelOptInfo *
3239 make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
3240 {
3241         Relids                  joinrelids;
3242         JoinMethodHint *hint;
3243         RelOptInfo         *rel;
3244         int                             save_nestlevel;
3245
3246         joinrelids = bms_union(rel1->relids, rel2->relids);
3247         hint = find_join_hint(joinrelids);
3248         bms_free(joinrelids);
3249
3250         if (!hint)
3251                 return pg_hint_plan_make_join_rel(root, rel1, rel2);
3252
3253         if (hint->inner_nrels == 0)
3254         {
3255                 save_nestlevel = NewGUCNestLevel();
3256
3257                 set_join_config_options(hint->enforce_mask, current_hint->context);
3258
3259                 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3260                 hint->base.state = HINT_STATE_USED;
3261
3262                 /*
3263                  * Restore the GUC variables we set above.
3264                  */
3265                 AtEOXact_GUC(true, save_nestlevel);
3266         }
3267         else
3268                 rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
3269
3270         return rel;
3271 }
3272
3273 /*
3274  * TODO : comment
3275  */
3276 static void
3277 add_paths_to_joinrel_wrapper(PlannerInfo *root,
3278                                                          RelOptInfo *joinrel,
3279                                                          RelOptInfo *outerrel,
3280                                                          RelOptInfo *innerrel,
3281                                                          JoinType jointype,
3282                                                          SpecialJoinInfo *sjinfo,
3283                                                          List *restrictlist)
3284 {
3285         ScanMethodHint *scan_hint = NULL;
3286         Relids                  joinrelids;
3287         JoinMethodHint *join_hint;
3288         int                             save_nestlevel;
3289
3290         if ((scan_hint = find_scan_hint(root, innerrel)) != NULL)
3291         {
3292                 set_scan_config_options(scan_hint->enforce_mask, current_hint->context);
3293                 scan_hint->base.state = HINT_STATE_USED;
3294         }
3295
3296         joinrelids = bms_union(outerrel->relids, innerrel->relids);
3297         join_hint = find_join_hint(joinrelids);
3298         bms_free(joinrelids);
3299
3300         if (join_hint && join_hint->inner_nrels != 0)
3301         {
3302                 save_nestlevel = NewGUCNestLevel();
3303
3304                 if (bms_equal(join_hint->inner_joinrelids, innerrel->relids))
3305                 {
3306
3307                         set_join_config_options(join_hint->enforce_mask,
3308                                                                         current_hint->context);
3309
3310                         add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3311                                                                  sjinfo, restrictlist);
3312                         join_hint->base.state = HINT_STATE_USED;
3313                 }
3314                 else
3315                 {
3316                         set_join_config_options(DISABLE_ALL_JOIN, current_hint->context);
3317                         add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3318                                                                  sjinfo, restrictlist);
3319                 }
3320
3321                 /*
3322                  * Restore the GUC variables we set above.
3323                  */
3324                 AtEOXact_GUC(true, save_nestlevel);
3325         }
3326         else
3327                 add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype,
3328                                                          sjinfo, restrictlist);
3329
3330         if (scan_hint != NULL)
3331                 set_scan_config_options(current_hint->init_scan_mask,
3332                                                                 current_hint->context);
3333 }
3334
3335 static int
3336 get_num_baserels(List *initial_rels)
3337 {
3338         int                     nbaserel = 0;
3339         ListCell   *l;
3340
3341         foreach(l, initial_rels)
3342         {
3343                 RelOptInfo *rel = (RelOptInfo *) lfirst(l);
3344
3345                 if (rel->reloptkind == RELOPT_BASEREL)
3346                         nbaserel++;
3347                 else if (rel->reloptkind ==RELOPT_JOINREL)
3348                         nbaserel+= bms_num_members(rel->relids);
3349                 else
3350                 {
3351                         /* other values not expected here */
3352                         elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
3353                 }
3354         }
3355
3356         return nbaserel;
3357 }
3358
3359 static RelOptInfo *
3360 pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
3361                                                  List *initial_rels)
3362 {
3363         JoinMethodHint    **join_method_hints;
3364         int                                     nbaserel;
3365         RelOptInfo                 *rel;
3366         int                                     i;
3367         bool                            leading_hint_enable;
3368
3369         /*
3370          * Use standard planner (or geqo planner) if pg_hint_plan is disabled or no
3371          * valid hint is supplied.
3372          */
3373         if (!current_hint)
3374         {
3375                 if (prev_join_search)
3376                         return (*prev_join_search) (root, levels_needed, initial_rels);
3377                 else if (enable_geqo && levels_needed >= geqo_threshold)
3378                         return geqo(root, levels_needed, initial_rels);
3379                 else
3380                         return standard_join_search(root, levels_needed, initial_rels);
3381         }
3382
3383         /* We apply scan method hint rebuild scan path. */
3384         rebuild_scan_path(current_hint, root, levels_needed, initial_rels);
3385
3386         /*
3387          * In the case using GEQO, only scan method hints and Set hints have
3388          * effect.  Join method and join order is not controllable by hints.
3389          */
3390         if (enable_geqo && levels_needed >= geqo_threshold)
3391                 return geqo(root, levels_needed, initial_rels);
3392
3393         nbaserel = get_num_baserels(initial_rels);
3394         current_hint->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
3395         join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
3396
3397         leading_hint_enable = transform_join_hints(current_hint, root, nbaserel,
3398                                                                                            initial_rels, join_method_hints);
3399
3400         rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
3401
3402         for (i = 2; i <= nbaserel; i++)
3403         {
3404                 list_free(current_hint->join_hint_level[i]);
3405
3406                 /* free Leading hint only */
3407                 if (join_method_hints[i] != NULL &&
3408                         join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
3409                         JoinMethodHintDelete(join_method_hints[i]);
3410         }
3411         pfree(current_hint->join_hint_level);
3412         pfree(join_method_hints);
3413
3414         if (leading_hint_enable)
3415                 set_join_config_options(current_hint->init_join_mask,
3416                                                                 current_hint->context);
3417
3418         return rel;
3419 }
3420
3421 /*
3422  * set_rel_pathlist
3423  *        Build access paths for a base relation
3424  *
3425  * This function was copied and edited from set_rel_pathlist() in
3426  * src/backend/optimizer/path/allpaths.c
3427  */
3428 static void
3429 set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
3430                                  Index rti, RangeTblEntry *rte)
3431 {
3432 #if PG_VERSION_NUM >= 90200
3433         if (IS_DUMMY_REL(rel))
3434         {
3435                 /* We already proved the relation empty, so nothing more to do */
3436         }
3437         else if (rte->inh)
3438 #else
3439         if (rte->inh)
3440 #endif
3441         {
3442                 /* It's an "append relation", process accordingly */
3443                 set_append_rel_pathlist(root, rel, rti, rte);
3444         }
3445         else
3446         {
3447                 if (rel->rtekind == RTE_RELATION)
3448                 {
3449                         if (rte->relkind == RELKIND_RELATION)
3450                         {
3451                                 /* Plain relation */
3452                                 set_plain_rel_pathlist(root, rel, rte);
3453                         }
3454                         else
3455                                 elog(ERROR, "unexpected relkind: %c", rte->relkind);
3456                 }
3457                 else
3458                         elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
3459         }
3460 }
3461
3462 #define standard_join_search pg_hint_plan_standard_join_search
3463 #define join_search_one_level pg_hint_plan_join_search_one_level
3464 #define make_join_rel make_join_rel_wrapper
3465 #include "core.c"
3466
3467 #undef make_join_rel
3468 #define make_join_rel pg_hint_plan_make_join_rel
3469 #define add_paths_to_joinrel add_paths_to_joinrel_wrapper
3470 #include "make_join_rel.c"