OSDN Git Service

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