OSDN Git Service

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