-
Notifications
You must be signed in to change notification settings - Fork 104
/
pg_hint_plan.c
4950 lines (4203 loc) · 123 KB
/
pg_hint_plan.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* pg_hint_plan.c
* hinting on how to execute a query for PostgreSQL
*
* Copyright (c) 2012-2024, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
*
*-------------------------------------------------------------------------
*/
#include <string.h>
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/relation.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_index.h"
#include "catalog/pg_proc.h"
#include "commands/prepare.h"
#include "commands/proclang.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "nodes/params.h"
#include "optimizer/appendinfo.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/geqo.h"
#include "optimizer/joininfo.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/scansup.h"
#include "partitioning/partbounds.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/float.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "catalog/pg_class.h"
#include "executor/spi.h"
#include "catalog/pg_type.h"
#include "plpgsql.h"
/* Owner scanner */
#include "query_scan.h"
/* PostgreSQL */
#include "access/htup_details.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
#define BLOCK_COMMENT_START "/*"
#define BLOCK_COMMENT_END "*/"
#define HINT_COMMENT_KEYWORD "+"
#define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
#define HINT_END BLOCK_COMMENT_END
/* hint keywords */
#define HINT_SEQSCAN "SeqScan"
#define HINT_INDEXSCAN "IndexScan"
#define HINT_INDEXSCANREGEXP "IndexScanRegexp"
#define HINT_BITMAPSCAN "BitmapScan"
#define HINT_BITMAPSCANREGEXP "BitmapScanRegexp"
#define HINT_TIDSCAN "TidScan"
#define HINT_NOSEQSCAN "NoSeqScan"
#define HINT_NOINDEXSCAN "NoIndexScan"
#define HINT_NOBITMAPSCAN "NoBitmapScan"
#define HINT_NOTIDSCAN "NoTidScan"
#define HINT_INDEXONLYSCAN "IndexOnlyScan"
#define HINT_INDEXONLYSCANREGEXP "IndexOnlyScanRegexp"
#define HINT_NOINDEXONLYSCAN "NoIndexOnlyScan"
#define HINT_PARALLEL "Parallel"
#define HINT_NESTLOOP "NestLoop"
#define HINT_MERGEJOIN "MergeJoin"
#define HINT_HASHJOIN "HashJoin"
#define HINT_NONESTLOOP "NoNestLoop"
#define HINT_NOMERGEJOIN "NoMergeJoin"
#define HINT_NOHASHJOIN "NoHashJoin"
#define HINT_LEADING "Leading"
#define HINT_SET "Set"
#define HINT_ROWS "Rows"
#define HINT_MEMOIZE "Memoize"
#define HINT_NOMEMOIZE "NoMemoize"
#define HINT_ARRAY_DEFAULT_INITSIZE 8
#define hint_ereport(str, detail) hint_parse_ereport(str, detail)
#define hint_parse_ereport(str, detail) \
do { \
ereport(pg_hint_plan_parse_message_level, \
(errmsg("pg_hint_plan: hint syntax error at or near \"%s\"", (str)), \
errdetail detail)); \
} while(0)
#define skip_space(str) \
while (isspace(*str)) \
str++;
enum SCAN_TYPE_BITS
{
ENABLE_SEQSCAN = 0x01,
ENABLE_INDEXSCAN = 0x02,
ENABLE_BITMAPSCAN = 0x04,
ENABLE_TIDSCAN = 0x08,
ENABLE_INDEXONLYSCAN = 0x10
};
enum JOIN_TYPE_BITS
{
ENABLE_NESTLOOP = 0x01,
ENABLE_MERGEJOIN = 0x02,
ENABLE_HASHJOIN = 0x04,
ENABLE_MEMOIZE = 0x08
};
#define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | \
ENABLE_BITMAPSCAN | ENABLE_TIDSCAN | \
ENABLE_INDEXONLYSCAN)
#define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
#define DISABLE_ALL_SCAN 0
#define DISABLE_ALL_JOIN 0
/* hint keyword of enum type*/
typedef enum HintKeyword
{
HINT_KEYWORD_SEQSCAN,
HINT_KEYWORD_INDEXSCAN,
HINT_KEYWORD_INDEXSCANREGEXP,
HINT_KEYWORD_BITMAPSCAN,
HINT_KEYWORD_BITMAPSCANREGEXP,
HINT_KEYWORD_TIDSCAN,
HINT_KEYWORD_NOSEQSCAN,
HINT_KEYWORD_NOINDEXSCAN,
HINT_KEYWORD_NOBITMAPSCAN,
HINT_KEYWORD_NOTIDSCAN,
HINT_KEYWORD_INDEXONLYSCAN,
HINT_KEYWORD_INDEXONLYSCANREGEXP,
HINT_KEYWORD_NOINDEXONLYSCAN,
HINT_KEYWORD_NESTLOOP,
HINT_KEYWORD_MERGEJOIN,
HINT_KEYWORD_HASHJOIN,
HINT_KEYWORD_NONESTLOOP,
HINT_KEYWORD_NOMERGEJOIN,
HINT_KEYWORD_NOHASHJOIN,
HINT_KEYWORD_LEADING,
HINT_KEYWORD_SET,
HINT_KEYWORD_ROWS,
HINT_KEYWORD_PARALLEL,
HINT_KEYWORD_MEMOIZE,
HINT_KEYWORD_NOMEMOIZE,
HINT_KEYWORD_UNRECOGNIZED
} HintKeyword;
#define SCAN_HINT_ACCEPTS_INDEX_NAMES(kw) \
(kw == HINT_KEYWORD_INDEXSCAN || \
kw == HINT_KEYWORD_INDEXSCANREGEXP || \
kw == HINT_KEYWORD_INDEXONLYSCAN || \
kw == HINT_KEYWORD_INDEXONLYSCANREGEXP || \
kw == HINT_KEYWORD_BITMAPSCAN || \
kw == HINT_KEYWORD_BITMAPSCANREGEXP)
typedef struct Hint Hint;
typedef struct HintState HintState;
typedef Hint *(*HintCreateFunction) (const char *hint_str,
const char *keyword,
HintKeyword hint_keyword);
typedef void (*HintDeleteFunction) (Hint *hint);
typedef void (*HintDescFunction) (Hint *hint, StringInfo buf, bool nolf);
typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
typedef const char *(*HintParseFunction) (Hint *hint, const char *str);
/* hint types */
typedef enum HintType
{
HINT_TYPE_SCAN_METHOD,
HINT_TYPE_JOIN_METHOD,
HINT_TYPE_LEADING,
HINT_TYPE_SET,
HINT_TYPE_ROWS,
HINT_TYPE_PARALLEL,
HINT_TYPE_MEMOIZE,
NUM_HINT_TYPE
} HintType;
typedef enum HintTypeBitmap
{
HINT_BM_SCAN_METHOD = 1,
HINT_BM_PARALLEL = 2
} HintTypeBitmap;
static const char *HintTypeName[] = {
"scan method",
"join method",
"leading",
"set",
"rows",
"parallel",
"memoize"
};
StaticAssertDecl(sizeof(HintTypeName) / sizeof(char *) == NUM_HINT_TYPE,
"HintTypeName and HintType don't match");
/* hint status */
typedef enum HintStatus
{
HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
HINT_STATE_USED, /* hint is used */
HINT_STATE_DUPLICATION, /* specified hint duplication */
HINT_STATE_ERROR /* execute error (parse error does not include
* it) */
} HintStatus;
#define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
(hint)->base.state == HINT_STATE_USED)
/* These variables are used only when debug_level > 1*/
static unsigned int qno = 0;
static unsigned int msgqno = 0;
static char qnostr[32];
static const char *current_hint_str = NULL;
/*
* We can utilize in-core generated jumble state in post_parse_analyze_hook.
* On the other hand there's a case where we're forced to get hints in
* planner_hook, where we don't have a jumble state. If we a query had not a
* hint, we need to try to retrieve hints twice or more for one query, which is
* the quite common case. To avoid such case, this variables is set true when
* we *try* hint retrieval.
*/
static bool current_hint_retrieved = false;
/* common data for all hints. */
struct Hint
{
const char *hint_str; /* must not do pfree */
const char *keyword; /* must not do pfree */
HintKeyword hint_keyword;
HintType type;
HintStatus state;
HintDeleteFunction delete_func;
HintDescFunction desc_func;
HintCmpFunction cmp_func;
HintParseFunction parse_func;
};
/* scan method hints */
typedef struct ScanMethodHint
{
Hint base;
char *relname;
List *indexnames;
bool regexp;
unsigned char enforce_mask;
} ScanMethodHint;
typedef struct ParentIndexInfo
{
bool indisunique;
Oid method;
List *column_names;
char *expression_str;
Oid *indcollation;
Oid *opclass;
int16 *indoption;
char *indpred_str;
} ParentIndexInfo;
/* join method hints */
typedef struct JoinMethodHint
{
Hint base;
int nrels;
int inner_nrels;
char **relnames;
unsigned char enforce_mask;
Relids joinrelids;
Relids inner_joinrelids;
} JoinMethodHint;
/* join order hints */
typedef struct OuterInnerRels
{
char *relation;
List *outer_inner_pair;
} OuterInnerRels;
typedef struct LeadingHint
{
Hint base;
List *relations; /* relation names specified in Leading hint */
OuterInnerRels *outer_inner;
} LeadingHint;
/* change a run-time parameter hints */
typedef struct SetHint
{
Hint base;
char *name; /* name of variable */
char *value;
List *words;
} SetHint;
/* rows hints */
typedef enum RowsValueType {
RVT_ABSOLUTE, /* Rows(... #1000) */
RVT_ADD, /* Rows(... +1000) */
RVT_SUB, /* Rows(... -1000) */
RVT_MULTI, /* Rows(... *1.2) */
} RowsValueType;
typedef struct RowsHint
{
Hint base;
int nrels;
int inner_nrels;
char **relnames;
Relids joinrelids;
Relids inner_joinrelids;
char *rows_str;
RowsValueType value_type;
double rows;
} RowsHint;
/* parallel hints */
typedef struct ParallelHint
{
Hint base;
char *relname;
char *nworkers_str; /* original string of nworkers */
int nworkers; /* num of workers specified by Worker */
bool force_parallel; /* force parallel scan */
} ParallelHint;
/*
* Describes a context of hint processing.
*/
struct HintState
{
char *hint_str; /* original hint string */
/* all hint */
int nall_hints; /* # of valid all hints */
int max_all_hints; /* # of slots for all hints */
Hint **all_hints; /* parsed all hints */
/* # of each hints */
int num_hints[NUM_HINT_TYPE];
/* for scan method hints */
ScanMethodHint **scan_hints; /* parsed scan hints */
/* Initial values of parameters */
int init_scan_mask; /* enable_* mask */
int init_nworkers; /* max_parallel_workers_per_gather */
/* min_parallel_table_scan_size*/
int init_min_para_tablescan_size;
/* min_parallel_index_scan_size*/
int init_min_para_indexscan_size;
double init_paratup_cost; /* parallel_tuple_cost */
double init_parasetup_cost;/* parallel_setup_cost */
PlannerInfo *current_root; /* PlannerInfo for the followings */
Index parent_relid; /* inherit parent of table relid */
ScanMethodHint *parent_scan_hint; /* scan hint for the parent */
ParallelHint *parent_parallel_hint; /* parallel hint for the parent */
List *parent_index_infos; /* list of parent table's index */
JoinMethodHint **join_hints; /* parsed join hints */
int init_join_mask; /* initial value join parameter */
List **join_hint_level;
List **memoize_hint_level;
LeadingHint **leading_hint; /* parsed Leading hints */
SetHint **set_hints; /* parsed Set hints */
GucContext context; /* which GUC parameters can we set? */
RowsHint **rows_hints; /* parsed Rows hints */
ParallelHint **parallel_hints; /* parsed Parallel hints */
JoinMethodHint **memoize_hints; /* parsed Memoize hints */
};
/*
* Describes a hint parser module which is bound with particular hint keyword.
*/
typedef struct HintParser
{
char *keyword;
HintCreateFunction create_func;
HintKeyword hint_keyword;
} HintParser;
static bool enable_hint_table_check(bool *newval, void **extra, GucSource source);
static void assign_enable_hint_table(bool newval, void *extra);
/* Module callbacks */
void _PG_init(void);
static void push_hint(HintState *hstate);
static void pop_hint(void);
static void pg_hint_plan_post_parse_analyze(ParseState *pstate, Query *query,
JumbleState *jstate);
static PlannedStmt *pg_hint_plan_planner(Query *parse, const char *query_string,
int cursorOptions,
ParamListInfo boundParams);
static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
int levels_needed,
List *initial_rels);
/* Scan method hint callbacks */
static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword);
static void ScanMethodHintDelete(ScanMethodHint *hint);
static void ScanMethodHintDesc(ScanMethodHint *hint, StringInfo buf, bool nolf);
static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
static const char *ScanMethodHintParse(ScanMethodHint *hint, const char *str);
/* Join method hint callbacks */
static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword);
static void JoinMethodHintDelete(JoinMethodHint *hint);
static void JoinMethodHintDesc(JoinMethodHint *hint, StringInfo buf, bool nolf);
static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
static const char *JoinMethodHintParse(JoinMethodHint *hint, const char *str);
/* Leading hint callbacks */
static Hint *LeadingHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword);
static void LeadingHintDelete(LeadingHint *hint);
static void LeadingHintDesc(LeadingHint *hint, StringInfo buf, bool nolf);
static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
static const char *LeadingHintParse(LeadingHint *hint, const char *str);
/* Set hint callbacks */
static Hint *SetHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword);
static void SetHintDelete(SetHint *hint);
static void SetHintDesc(SetHint *hint, StringInfo buf, bool nolf);
static int SetHintCmp(const SetHint *a, const SetHint *b);
static const char *SetHintParse(SetHint *hint, const char *str);
/* Rows hint callbacks */
static Hint *RowsHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword);
static void RowsHintDelete(RowsHint *hint);
static void RowsHintDesc(RowsHint *hint, StringInfo buf, bool nolf);
static int RowsHintCmp(const RowsHint *a, const RowsHint *b);
static const char *RowsHintParse(RowsHint *hint, const char *str);
/* Parallel hint callbacks */
static Hint *ParallelHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword);
static void ParallelHintDelete(ParallelHint *hint);
static void ParallelHintDesc(ParallelHint *hint, StringInfo buf, bool nolf);
static int ParallelHintCmp(const ParallelHint *a, const ParallelHint *b);
static const char *ParallelHintParse(ParallelHint *hint, const char *str);
static Hint *MemoizeHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword);
static void quote_value(StringInfo buf, const char *value);
static const char *parse_quoted_value(const char *str, char **word,
bool truncate);
RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
int levels_needed,
List *initial_rels);
void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
void pg_hint_plan_set_rel_pathlist(PlannerInfo * root, RelOptInfo *rel,
Index rti, RangeTblEntry *rte);
static void create_plain_partial_paths(PlannerInfo *root,
RelOptInfo *rel);
static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
List *other_rels,
int first_rel_idx);
static void make_rels_by_clauseless_joins(PlannerInfo *root,
RelOptInfo *old_rel,
List *other_rels);
static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
RangeTblEntry *rte);
static void free_child_join_sjinfo(SpecialJoinInfo *sjinfo);
RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
RelOptInfo *rel2);
static int set_config_option_noerror(const char *name, const char *value,
GucContext context, GucSource source,
GucAction action, bool changeVal, int elevel);
static void setup_scan_method_enforcement(ScanMethodHint *scanhint,
HintState *state);
static int set_config_int32_option(const char *name, int32 value,
GucContext context);
static int set_config_double_option(const char *name, double value,
GucContext context);
/* GUC variables */
static bool pg_hint_plan_enable_hint = true;
static int debug_level = 0;
static int pg_hint_plan_parse_message_level = INFO;
static int pg_hint_plan_debug_message_level = LOG;
/* Default is off, to keep backward compatibility. */
static bool pg_hint_plan_enable_hint_table = false;
static int plpgsql_recurse_level = 0; /* PLpgSQL recursion level */
static int recurse_level = 0; /* recursion level incl. direct SPI calls */
static int hint_inhibit_level = 0; /* Inhibit hinting if this is above 0 */
/* (This could not be above 1) */
static int max_hint_nworkers = -1; /* Maximum nworkers of Workers hints */
static bool hint_table_deactivated = false;
static const struct config_enum_entry parse_messages_level_options[] = {
{"debug", DEBUG2, true},
{"debug5", DEBUG5, false},
{"debug4", DEBUG4, false},
{"debug3", DEBUG3, false},
{"debug2", DEBUG2, false},
{"debug1", DEBUG1, false},
{"log", LOG, false},
{"info", INFO, false},
{"notice", NOTICE, false},
{"warning", WARNING, false},
{"error", ERROR, false},
/*
* {"fatal", FATAL, true},
* {"panic", PANIC, true},
*/
{NULL, 0, false}
};
static const struct config_enum_entry parse_debug_level_options[] = {
{"off", 0, false},
{"on", 1, false},
{"detailed", 2, false},
{"verbose", 3, false},
{"0", 0, true},
{"1", 1, true},
{"2", 2, true},
{"3", 3, true},
{"no", 0, true},
{"yes", 1, true},
{"false", 0, true},
{"true", 1, true},
{NULL, 0, false}
};
/* Saved hook values in case of unload */
static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
static planner_hook_type prev_planner = NULL;
static join_search_hook_type prev_join_search = NULL;
static set_rel_pathlist_hook_type prev_set_rel_pathlist = NULL;
static needs_fmgr_hook_type prev_needs_fmgr_hook = NULL;
static fmgr_hook_type prev_fmgr_hook = NULL;
static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
/* Hold reference to currently active hint */
static HintState *current_hint_state = NULL;
/*
* Reference to OID of PL/pgsql language, saved on first lookup at a
* PL function.
*/
static Oid pg_hint_plan_pgpg_oid = InvalidOid;
/*
* List of hint contexts. We treat the head of the list as the Top of the
* context stack, so current_hint_state always points the first element of this
* list.
*/
static List *HintStateStack = NIL;
static const HintParser parsers[] = {
{HINT_SEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_SEQSCAN},
{HINT_INDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCAN},
{HINT_INDEXSCANREGEXP, ScanMethodHintCreate, HINT_KEYWORD_INDEXSCANREGEXP},
{HINT_BITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_BITMAPSCAN},
{HINT_BITMAPSCANREGEXP, ScanMethodHintCreate,
HINT_KEYWORD_BITMAPSCANREGEXP},
{HINT_TIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_TIDSCAN},
{HINT_NOSEQSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOSEQSCAN},
{HINT_NOINDEXSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXSCAN},
{HINT_NOBITMAPSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOBITMAPSCAN},
{HINT_NOTIDSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOTIDSCAN},
{HINT_INDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_INDEXONLYSCAN},
{HINT_INDEXONLYSCANREGEXP, ScanMethodHintCreate,
HINT_KEYWORD_INDEXONLYSCANREGEXP},
{HINT_NOINDEXONLYSCAN, ScanMethodHintCreate, HINT_KEYWORD_NOINDEXONLYSCAN},
{HINT_NESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NESTLOOP},
{HINT_MERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_MERGEJOIN},
{HINT_HASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_HASHJOIN},
{HINT_NONESTLOOP, JoinMethodHintCreate, HINT_KEYWORD_NONESTLOOP},
{HINT_NOMERGEJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOMERGEJOIN},
{HINT_NOHASHJOIN, JoinMethodHintCreate, HINT_KEYWORD_NOHASHJOIN},
{HINT_LEADING, LeadingHintCreate, HINT_KEYWORD_LEADING},
{HINT_SET, SetHintCreate, HINT_KEYWORD_SET},
{HINT_ROWS, RowsHintCreate, HINT_KEYWORD_ROWS},
{HINT_PARALLEL, ParallelHintCreate, HINT_KEYWORD_PARALLEL},
{HINT_MEMOIZE, MemoizeHintCreate, HINT_KEYWORD_MEMOIZE},
{HINT_NOMEMOIZE, MemoizeHintCreate, HINT_KEYWORD_NOMEMOIZE},
{NULL, NULL, HINT_KEYWORD_UNRECOGNIZED}
};
static bool
pg_hint_plan_is_plpgsql_function(Oid funcoid)
{
HeapTuple procTuple;
Form_pg_proc procStruct;
bool result;
procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
if (!HeapTupleIsValid(procTuple))
return false;
procStruct = (Form_pg_proc) GETSTRUCT(procTuple);
if (!OidIsValid(pg_hint_plan_pgpg_oid))
pg_hint_plan_pgpg_oid = get_language_oid("plpgsql", false);
result = (procStruct->prolang == pg_hint_plan_pgpg_oid);
ReleaseSysCache(procTuple);
return result;
}
/*
* Used as needs_fmgr_hook. All plpgsql functions needs this hook to properly
* track the nested depth of plpgsql calls.
*/
static bool
pg_hint_plan_needs_fmgr_hook(Oid funcoid)
{
if (prev_needs_fmgr_hook &&
(*prev_needs_fmgr_hook)(funcoid))
return true;
return pg_hint_plan_is_plpgsql_function(funcoid);
}
static void
pg_hint_plan_fmgr_hook(FmgrHookEventType event,
FmgrInfo *flinfo, Datum *private)
{
if (prev_fmgr_hook)
(*prev_fmgr_hook) (event, flinfo, private);
switch (event)
{
case FHET_START:
plpgsql_recurse_level++;
Assert(plpgsql_recurse_level > 0);
break;
case FHET_END:
case FHET_ABORT: /* may be an exception */
plpgsql_recurse_level--;
Assert(plpgsql_recurse_level >= 0);
break;
default:
break;
}
return;
}
/*
* pg_hint_ExecutorEnd
*
* Force a hint to be retrieved when we are at the top of a PL recursion
* level. This can become necessary to handle hints in queries executed
* in the extended protocol, where the executor can be executed multiple
* times in a portal, but it could be possible to fail the hint retrieval.
*/
static void
pg_hint_ExecutorEnd(QueryDesc *queryDesc)
{
if (plpgsql_recurse_level == 0)
current_hint_retrieved = false;
if (prev_ExecutorEnd)
prev_ExecutorEnd(queryDesc);
else
standard_ExecutorEnd(queryDesc);
}
/*
* Module load callbacks
*/
void
_PG_init(void)
{
/* Define custom GUC variables. */
DefineCustomBoolVariable("pg_hint_plan.enable_hint",
"Force planner to use plans specified in the hint comment preceding to the query.",
NULL,
&pg_hint_plan_enable_hint,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_hint_plan.debug_print",
"Logs results of hint parsing.",
NULL,
&debug_level,
false,
parse_debug_level_options,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_hint_plan.parse_messages",
"Message level of parse errors.",
NULL,
&pg_hint_plan_parse_message_level,
INFO,
parse_messages_level_options,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_hint_plan.message_level",
"Message level of debug messages.",
NULL,
&pg_hint_plan_debug_message_level,
LOG,
parse_messages_level_options,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_hint_plan.enable_hint_table",
"Let pg_hint_plan look up the hint table.",
NULL,
&pg_hint_plan_enable_hint_table,
false,
PGC_USERSET,
0,
enable_hint_table_check,
assign_enable_hint_table,
NULL);
EmitWarningsOnPlaceholders("pg_hint_plan");
/* Install hooks. */
prev_post_parse_analyze_hook = post_parse_analyze_hook;
post_parse_analyze_hook = pg_hint_plan_post_parse_analyze;
prev_planner = planner_hook;
planner_hook = pg_hint_plan_planner;
prev_join_search = join_search_hook;
join_search_hook = pg_hint_plan_join_search;
prev_set_rel_pathlist = set_rel_pathlist_hook;
set_rel_pathlist_hook = pg_hint_plan_set_rel_pathlist;
prev_fmgr_hook = fmgr_hook;
fmgr_hook = pg_hint_plan_fmgr_hook;
prev_needs_fmgr_hook = needs_fmgr_hook;
needs_fmgr_hook = pg_hint_plan_needs_fmgr_hook;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pg_hint_ExecutorEnd;
}
static bool
enable_hint_table_check(bool *newval, void **extra, GucSource source)
{
if (*newval)
{
EnableQueryId();
if (!IsQueryIdEnabled())
{
GUC_check_errmsg("table hint is not activated because queryid is not available");
GUC_check_errhint("Set compute_query_id to on or auto to use hint table.");
return false;
}
}
return true;
}
static void
assign_enable_hint_table(bool newval, void *extra)
{
if (!newval)
hint_table_deactivated = false;
}
/*
* create and delete functions the hint object
*/
static Hint *
ScanMethodHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword)
{
ScanMethodHint *hint;
hint = palloc0(sizeof(ScanMethodHint));
hint->base.hint_str = hint_str;
hint->base.keyword = keyword;
hint->base.hint_keyword = hint_keyword;
hint->base.type = HINT_TYPE_SCAN_METHOD;
hint->base.state = HINT_STATE_NOTUSED;
hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
hint->base.desc_func = (HintDescFunction) ScanMethodHintDesc;
hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
hint->base.parse_func = (HintParseFunction) ScanMethodHintParse;
hint->relname = NULL;
hint->indexnames = NIL;
hint->regexp = false;
hint->enforce_mask = 0;
return (Hint *) hint;
}
static void
ScanMethodHintDelete(ScanMethodHint *hint)
{
if (!hint)
return;
if (hint->relname)
pfree(hint->relname);
list_free_deep(hint->indexnames);
pfree(hint);
}
static Hint *
JoinMethodHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword)
{
JoinMethodHint *hint;
hint = palloc0(sizeof(JoinMethodHint));
hint->base.hint_str = hint_str;
hint->base.keyword = keyword;
hint->base.hint_keyword = hint_keyword;
hint->base.type = HINT_TYPE_JOIN_METHOD;
hint->base.state = HINT_STATE_NOTUSED;
hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
hint->base.desc_func = (HintDescFunction) JoinMethodHintDesc;
hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
hint->base.parse_func = (HintParseFunction) JoinMethodHintParse;
hint->nrels = 0;
hint->inner_nrels = 0;
hint->relnames = NULL;
hint->enforce_mask = 0;
hint->joinrelids = NULL;
hint->inner_joinrelids = NULL;
return (Hint *) hint;
}
static void
JoinMethodHintDelete(JoinMethodHint *hint)
{
if (!hint)
return;
if (hint->relnames)
{
int i;
for (i = 0; i < hint->nrels; i++)
pfree(hint->relnames[i]);
pfree(hint->relnames);
}
bms_free(hint->joinrelids);
bms_free(hint->inner_joinrelids);
pfree(hint);
}
static Hint *
LeadingHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword)
{
LeadingHint *hint;
hint = palloc0(sizeof(LeadingHint));
hint->base.hint_str = hint_str;
hint->base.keyword = keyword;
hint->base.hint_keyword = hint_keyword;
hint->base.type = HINT_TYPE_LEADING;
hint->base.state = HINT_STATE_NOTUSED;
hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
hint->base.desc_func = (HintDescFunction) LeadingHintDesc;
hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
hint->base.parse_func = (HintParseFunction) LeadingHintParse;
hint->relations = NIL;
hint->outer_inner = NULL;
return (Hint *) hint;
}
static void
LeadingHintDelete(LeadingHint *hint)
{
if (!hint)
return;
list_free_deep(hint->relations);
if (hint->outer_inner)
pfree(hint->outer_inner);
pfree(hint);
}
static Hint *
SetHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword)
{
SetHint *hint;
hint = palloc0(sizeof(SetHint));
hint->base.hint_str = hint_str;
hint->base.keyword = keyword;
hint->base.hint_keyword = hint_keyword;
hint->base.type = HINT_TYPE_SET;
hint->base.state = HINT_STATE_NOTUSED;
hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
hint->base.desc_func = (HintDescFunction) SetHintDesc;
hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
hint->base.parse_func = (HintParseFunction) SetHintParse;
hint->name = NULL;
hint->value = NULL;
hint->words = NIL;
return (Hint *) hint;
}
static void
SetHintDelete(SetHint *hint)
{
if (!hint)
return;
if (hint->name)
pfree(hint->name);
if (hint->value)
pfree(hint->value);
if (hint->words)
list_free(hint->words);
pfree(hint);
}
static Hint *
RowsHintCreate(const char *hint_str, const char *keyword,
HintKeyword hint_keyword)
{
RowsHint *hint;
hint = palloc0(sizeof(RowsHint));
hint->base.hint_str = hint_str;
hint->base.keyword = keyword;
hint->base.hint_keyword = hint_keyword;
hint->base.type = HINT_TYPE_ROWS;
hint->base.state = HINT_STATE_NOTUSED;
hint->base.delete_func = (HintDeleteFunction) RowsHintDelete;
hint->base.desc_func = (HintDescFunction) RowsHintDesc;
hint->base.cmp_func = (HintCmpFunction) RowsHintCmp;
hint->base.parse_func = (HintParseFunction) RowsHintParse;
hint->nrels = 0;
hint->inner_nrels = 0;
hint->relnames = NULL;
hint->joinrelids = NULL;
hint->inner_joinrelids = NULL;
hint->rows_str = NULL;
hint->value_type = RVT_ABSOLUTE;
hint->rows = 0;