OSDN Git Service

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