OSDN Git Service

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