OSDN Git Service

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