OSDN Git Service

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