OSDN Git Service

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