OSDN Git Service

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