OSDN Git Service

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