OSDN Git Service

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