OSDN Git Service

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