OSDN Git Service

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