OSDN Git Service

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