OSDN Git Service

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