OSDN Git Service

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