OSDN Git Service

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