OSDN Git Service

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