OSDN Git Service

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