-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhints.rs
More file actions
1018 lines (930 loc) · 35.6 KB
/
hints.rs
File metadata and controls
1018 lines (930 loc) · 35.6 KB
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
use tracing::trace;
use crate::hint_engine::LeafNode;
use crate::hint_engine::{
GucParam, InternalNode, JoinAlgorithm, JoinNode, ParallelHint,
ParallelMode, ScanMethod, engine::HintEngineConfig,
};
use std::fmt;
/// Enum for different classes of Postgres hints
///
/// See [Postgres Documentation](https://pg-hint-plan.readthedocs.io/en/latest/hint_list.html) for more details
///
/// Used to configure engine
///
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
/// Supported hint groups for pg_hint_plan. See [pg_hint_plan](https://pg-hint-plan.readthedocs.io/en/latest/hint_list.html) for more details.
///
/// For supported variants of each group, see the `PgHint` enum.
///
/// # Variants
///
/// - JoinOrder: Specifies the join order of tables in a query. Output: Leading(t1 t2 t3)
/// - JoinOrderInnerOuter: Similar to JoinOrder, but preserves inner/outer table for each join. Output: Leading(((t1 t2) t3))
/// - JoinMethod: Specifies the join algorithm to use for joins. Output: HashJoin(t1 t2) also represents negative join methods like NoHashJoin(t1 t2)
/// - ScanMethod: Specifies the scan method to use for tables. Output: SeqScan(t1), IndexScan(t1 idx1), etc. Also represents negative scan methods like NoSeqScan(t1)
/// - RowNumberCorrection: Specifies the estimated number of rows for a table or join. Output: Rows(t1 t2 #1000)
/// - JoinMemoize: Specifies the join behavior (e.g., memoization) for joins. Output: Memoize(t1 t2)
pub enum PGHintType {
JoinOrder,
JoinOrderInnerOuter,
JoinMethod,
ScanMethod,
RowNumberCorrection,
JoinMemoize,
GucParameter,
Parallel,
}
/// Represents postgres hints
///
///
/// Represents a list of postgres hints.
///
/// The each hint references the join tree and only generates the hint text when formatted to string.
///
/// The native to_string method outputs the hints in the format required by pg_hint_plan.
/// # Fields
/// * `hints`: A vector of postgres hints
/// * `data`: The join tree that the hints are based on
/// * `config`: The configuration for the hint engine (which groups of hints to use, etc)
/// # Methods
/// * `new`: Creates a new empty hint list with the given configuration
/// * `add_hint`: Adds a hint to the hint list
/// * `size`: Returns the number of hints in the hint list
/// * `to_hint_table_string`: Returns the hints as a single string, concatenated by spaces (for use in a hint table)
/// * `from_join_tree`: Creates a hint list from a join tree and configuration
/// * `from_join_node`: Recursively adds hints from a join node (used by from_join_tree)
/// * `with_sql`: Returns the SQL representation of the hint list, prepended to the given SQL query
/// * `fmt::Display`: Formats the hint list as a string in the format required by pg_hint_plan
///
#[derive(Clone, Debug)]
pub struct PgHintList<'a> {
hints: Vec<PgHint<'a>>,
data: JoinNode,
config: HintEngineConfig,
}
impl<'a> PgHintList<'a> {
pub fn new(config: HintEngineConfig) -> Self {
PgHintList {
hints: Vec::new(),
data: JoinNode::Leaf(LeafNode::new("".to_string())),
config,
}
}
pub fn get_data(&self) -> &JoinNode {
&self.data
}
//// Get the length of the hint list
//// Returns:
//// - length of the hint list
pub fn size(&self) -> usize {
self.hints.len()
}
/// output hints concatenated by space, used for hint table
/// Returns:
/// - string of hints concatenated by space
#[cfg(feature = "hint-table")]
pub fn to_hint_table_string(&self) -> String {
self.hints
.iter()
.map(|h| h.to_string())
.collect::<Vec<_>>()
.join(" ")
}
/// Add a hint to the hint list
///
/// Should be used to add global hints that do not refer to join tree nodes. e.g., GUC Parameter hints
pub fn add_hint(&mut self, hint: PgHint<'a>) {
self.hints.push(hint);
}
/// Insert the hints into the pg_hint_plan hint table
///
/// If hints for this query_id already exist, they will be overwritten.
///
/// Arguments:
/// * `client`: The Postgres client to use for the insertion
/// * `query_id`: The query ID to associate the hints with
/// Returns:
/// * `Result<(), postgres::Error>`: Ok if successful, Err if there was an error
#[cfg(feature = "hint-table")]
pub fn insert_into_hint_table(
&self,
client: &mut postgres::Client,
query_id: i64,
) -> Result<(), postgres::Error> {
let hint_string = self.to_hint_table_string();
trace!("Inserting hints for query_id {}: {}", query_id, hint_string);
client.execute(
"INSERT INTO hint_plan.hints (query_id, application_name, hints) VALUES ($1, '', $2)
ON CONFLICT (query_id, application_name) DO UPDATE SET hints = EXCLUDED.hints",
&[&query_id, &hint_string],
)?;
Ok(())
}
/// Create a PgHintList from a join tree and configuration
///
/// TODO (bobby): Should this be part of engine?
///
/// Arguments:
/// * `root_node`: The root of the join tree, containing all children. Must be an InternalNode
/// * `config`: The configuration for the hint engine (which groups of hints to use
///
/// Returns:
/// * `Result<PgHintList, String>`: The generated hint list or an error message
//// Note: This replaces the previous add_hint and concat_hint_list methods
///
pub fn from_join_tree(
root_node: &'a JoinNode,
config: HintEngineConfig,
) -> Result<PgHintList<'a>, String> {
let mut hint_list = PgHintList::new(config);
hint_list.data = root_node.clone();
hint_list.hints = Vec::new();
// Add query level hints (Leading)
if let JoinNode::Internal(internal) = root_node {
if hint_list.config.is_hint_enabled(&PGHintType::JoinOrder) {
hint_list.hints.push(PgHint::JoinOrder {
join_order: &internal,
});
} else if hint_list
.config
.is_hint_enabled(&PGHintType::JoinOrderInnerOuter)
{
hint_list.hints.push(PgHint::JoinOrderInnerOuter {
join_order: &internal,
});
}
}
// Begin recursion to add the rest of the hints
hint_list.from_join_node(&root_node)?;
Ok(hint_list)
}
/// Helper function to traverse join tree and add appriopriate hints based on configuration
fn from_join_node(&mut self, node: &'a JoinNode) -> Result<(), String> {
match node {
JoinNode::Leaf(leaf) => {
if self.config.is_hint_enabled(&PGHintType::ScanMethod) {
match &leaf.scan_method {
ScanMethod::SeqScan => {
self.hints.push(PgHint::SeqScan { table: leaf })
}
ScanMethod::Index(index_name) => {
self.hints.push(PgHint::IndexScan {
table: leaf,
index: index_name.clone().into(),
})
}
ScanMethod::IndexOnly(index_name) => {
self.hints.push(PgHint::IndexOnlyScan {
table: leaf,
index: index_name.clone().into(),
})
}
ScanMethod::BitmapScan => {
self.hints.push(PgHint::BitmapScan { table: leaf })
}
ScanMethod::TidScan => {
self.hints.push(PgHint::TidScan { table: leaf })
}
ScanMethod::NoSeqScan => {
self.hints.push(PgHint::NoSeqScan { table: leaf })
}
ScanMethod::NoTidScan => {
self.hints.push(PgHint::NoTidScan { table: leaf })
}
ScanMethod::NoIndexScan => {
self.hints.push(PgHint::NoIndexScan { table: leaf })
}
ScanMethod::NoIndexOnlyScan => self
.hints
.push(PgHint::NoIndexOnlyScan { table: leaf }),
ScanMethod::NoBitmapScan => self
.hints
.push(PgHint::NoBitmapScan { table: leaf }),
ScanMethod::IndexRegex(pattern) => {
self.hints.push(PgHint::IndexScanRegexp {
table: leaf,
pattern: pattern.clone(),
})
}
ScanMethod::IndexOnlyRegex(pattern) => {
self.hints.push(PgHint::IndexOnlyScanRegexp {
table: leaf,
pattern: pattern.clone(),
})
}
ScanMethod::BitmapRegex(pattern) => {
self.hints.push(PgHint::BitmapScanRegexp {
table: leaf,
pattern: pattern.clone(),
})
}
ScanMethod::Unknown => {}
}
}
if self.config.is_hint_enabled(&PGHintType::Parallel) {
if let Some(parallel_hint) = &leaf.parallel_hint {
self.hints.push(PgHint::Parallel {
table: leaf,
hint: parallel_hint.clone(),
});
}
}
}
JoinNode::Internal(internal) => {
if self.config.is_hint_enabled(&PGHintType::JoinMethod) {
match internal.join_algorithm {
JoinAlgorithm::HashJoin => self
.hints
.push(PgHint::HashJoin { node: &internal }),
JoinAlgorithm::MergeJoin => self
.hints
.push(PgHint::MergeJoin { node: &internal }),
JoinAlgorithm::NestedLoopJoin => self
.hints
.push(PgHint::NestLoop { node: &internal }),
JoinAlgorithm::NoHashJoin => self
.hints
.push(PgHint::NoHashJoin { node: &internal }),
JoinAlgorithm::NoMergeJoin => self
.hints
.push(PgHint::NoMergeJoin { node: &internal }),
JoinAlgorithm::NoNestedLoopJoin => self
.hints
.push(PgHint::NoNestLoop { node: &internal }),
JoinAlgorithm::Unknown => {}
}
}
let tables: Vec<String> = internal
.print_tables(false)
.unwrap_or_default()
.trim()
.split_whitespace()
.map(|s| s.to_string())
.collect();
if self.config.is_hint_enabled(&PGHintType::JoinMemoize) {
if let Some(memoize) = internal.memoize {
if memoize {
self.hints
.push(PgHint::Memoize { node: &internal });
} else {
self.hints
.push(PgHint::NoMemoize { node: &internal });
}
}
}
if self
.config
.is_hint_enabled(&PGHintType::RowNumberCorrection)
{
if let Some(card) = internal.join_card {
self.hints.push(PgHint::CardCorrection {
tables: tables.clone(),
card: card as i64,
});
}
}
self.from_join_node(&internal.inner)?;
self.from_join_node(&internal.outer)?;
}
}
Ok(())
}
/// Returns the SQL representation of the hint list, prepended to the given SQL query
///
/// Arguments:
/// sql: The SQL query to prepend the hints to
/// Returns:
/// A string containing the hints followed by the SQL query
/// If there are no hints, returns the original SQL query
pub fn with_sql(&self, sql: &str) -> String {
if self.hints.is_empty() {
return sql.to_string();
}
format!("{}\n{}", self.to_string(), sql)
}
}
impl fmt::Display for PgHintList<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.hints.is_empty() {
return write!(f, "");
}
write!(
f,
"/*+ {} */",
self.hints
.iter()
.map(|h| h.to_string())
.collect::<Vec<_>>()
.join("\n")
)
}
}
// Can add more hints here, just be sure to implement fmt::Display for them
#[derive(Clone, Debug)]
pub enum PgHint<'a> {
SeqScan {
table: &'a LeafNode,
},
IndexScan {
table: &'a LeafNode,
index: Option<String>,
},
NoSeqScan {
table: &'a LeafNode,
},
NoTidScan {
table: &'a LeafNode,
},
NoIndexScan {
table: &'a LeafNode,
},
NoIndexOnlyScan {
table: &'a LeafNode,
},
NoBitmapScan {
table: &'a LeafNode,
},
BitmapScan {
table: &'a LeafNode,
},
TidScan {
table: &'a LeafNode,
},
JoinOrder {
join_order: &'a InternalNode,
},
JoinOrderInnerOuter {
// Variant to preserve inner/outer table for each join
join_order: &'a InternalNode,
},
HashJoin {
node: &'a InternalNode,
},
MergeJoin {
node: &'a InternalNode,
},
IndexOnlyScan {
table: &'a LeafNode,
index: Option<String>,
},
NestLoop {
node: &'a InternalNode,
},
CardCorrection {
tables: Vec<String>,
card: i64,
},
NoNestLoop {
node: &'a InternalNode,
},
NoHashJoin {
node: &'a InternalNode,
},
NoMergeJoin {
node: &'a InternalNode,
},
Parallel {
table: &'a LeafNode,
hint: ParallelHint,
},
NoParallel {
table: &'a LeafNode,
},
Memoize {
node: &'a InternalNode,
},
NoMemoize {
node: &'a InternalNode,
},
Set {
param: GucParam,
},
IndexScanRegexp {
table: &'a LeafNode,
pattern: String,
},
IndexOnlyScanRegexp {
table: &'a LeafNode,
pattern: String,
},
BitmapScanRegexp {
table: &'a LeafNode,
pattern: String,
},
}
impl fmt::Display for PgHint<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PgHint::SeqScan { table } => {
f.write_str(&format!("SeqScan({})", table.get_effective_name()))
}
PgHint::IndexScan { table, index } => {
if let Some(index) = index {
f.write_str(&format!(
"IndexScan({} {})",
table.get_effective_name(),
index
))
} else {
f.write_str(&format!(
"IndexScan({})",
table.get_effective_name()
))
}
}
PgHint::NoSeqScan { table } => f.write_str(&format!(
"NoSeqScan({})",
table.get_effective_name()
)),
PgHint::NoTidScan { table } => f.write_str(&format!(
"NoTidScan({})",
table.get_effective_name()
)),
PgHint::NoBitmapScan { table } => f.write_str(&format!(
"NoBitmapScan({})",
table.get_effective_name()
)),
PgHint::NoIndexScan { table } => f.write_str(&format!(
"NoIndexScan({})",
table.get_effective_name()
)),
PgHint::NoIndexOnlyScan { table } => f.write_str(&format!(
"NoIndexOnlyScan({})",
table.get_effective_name()
)),
PgHint::JoinOrder { join_order } => f.write_str(&format!(
"Leading({})",
(**join_order)
.print_tables(false)
.unwrap_or_default()
.trim()
)),
PgHint::JoinOrderInnerOuter { join_order } => {
f.write_str(&format!(
"Leading({})",
(**join_order)
.print_tables(true)
.unwrap_or_default()
.trim()
))
}
PgHint::HashJoin { node } => f.write_str(&format!(
"HashJoin({})",
node.print_tables(false).unwrap_or_default().trim()
)),
PgHint::MergeJoin { node } => f.write_str(&format!(
"MergeJoin({})",
node.print_tables(false).unwrap_or_default().trim()
)),
PgHint::NestLoop { node } => f.write_str(&format!(
"NestLoop({})",
node.print_tables(false).unwrap_or_default().trim()
)),
PgHint::IndexOnlyScan { table, index } => {
if let Some(index) = index {
f.write_str(&format!(
"IndexOnlyScan({} {})",
table.get_effective_name(),
index
))
} else {
f.write_str(&format!(
"IndexOnlyScan({})",
table.get_effective_name()
))
}
}
PgHint::BitmapScan { table } => f.write_str(&format!(
"BitmapScan({})",
table.get_effective_name()
)),
PgHint::TidScan { table } => {
f.write_str(&format!("TidScan({})", table.get_effective_name()))
}
PgHint::CardCorrection { tables, card } => {
f.write_str(&format!("Rows({} #{})", tables.join(" "), card))
}
PgHint::NoNestLoop { node } => f.write_str(&format!(
"NoNestLoop({})",
node.print_tables(false).unwrap_or_default().trim()
)),
PgHint::NoHashJoin { node } => f.write_str(&format!(
"NoHashJoin({})",
node.print_tables(false).unwrap_or_default().trim()
)),
PgHint::NoMergeJoin { node } => f.write_str(&format!(
"NoMergeJoin({})",
node.print_tables(false).unwrap_or_default().trim()
)),
PgHint::Parallel { table, hint } => {
let mode_str = match &hint.mode {
Some(ParallelMode::Soft) => " soft",
Some(ParallelMode::Hard) => " hard",
None => "",
};
f.write_str(&format!(
"Parallel({} {}{})",
table.get_effective_name(),
hint.workers,
mode_str
))
}
PgHint::NoParallel { table } => f.write_str(&format!(
"NoParallel({})",
table.get_effective_name()
)),
PgHint::Memoize { node } => f.write_str(&format!(
"Memoize({})",
node.print_tables(false).unwrap_or_default().trim()
)),
PgHint::NoMemoize { node } => f.write_str(&format!(
"NoMemoize({})",
node.print_tables(false).unwrap_or_default().trim()
)),
PgHint::Set { param } => f.write_str(&format!(
"Set({} {})",
param.parameter, param.value
)),
PgHint::IndexScanRegexp { table, pattern } => {
f.write_str(&format!(
"IndexScanRegexp({} {})",
table.get_effective_name(),
pattern
))
}
PgHint::IndexOnlyScanRegexp { table, pattern } => {
f.write_str(&format!(
"IndexOnlyScanRegexp({} {})",
table.get_effective_name(),
pattern
))
}
PgHint::BitmapScanRegexp { table, pattern } => {
f.write_str(&format!(
"BitmapScanRegexp({} {})",
table.get_effective_name(),
pattern
))
}
}
}
}
// TODO: Add tests for new functionality
#[cfg(test)]
mod test_hints {
use super::*;
#[allow(unused_imports)]
use crate::hint_engine::{
JoinAlgorithm, LeafNode, PlanNodeMetadata, engine::HintEngineConfig,
hints::PGHintType, visitor::PlanVisitor,
};
#[test]
fn test_hint_display() {
let hint = PgHint::SeqScan {
table: &LeafNode {
table_name: "title_basics".to_string(),
table_alias: None,
scan_method: ScanMethod::SeqScan,
parallel_hint: None,
},
};
assert_eq!(hint.to_string(), "SeqScan(title_basics)");
// TODO(bobby): Add scan method hints
let scan_tree = JoinNode::Internal(InternalNode {
inner: Box::new(JoinNode::Leaf(
LeafNode::new("title_basics".to_string())
.with_scan_method(ScanMethod::SeqScan),
)),
outer: Box::new(JoinNode::Leaf(
LeafNode::new("title_ratings".to_string()).with_scan_method(
ScanMethod::Index("idx_title_ratings_tconst".to_string()),
),
)),
join_algorithm: JoinAlgorithm::HashJoin,
join_card: None,
memoize: None,
});
let scan_only_config = HintEngineConfig::new()
.with_hint_type(PGHintType::ScanMethod)
.build();
let hint_list =
PgHintList::from_join_tree(&scan_tree, scan_only_config).unwrap();
// assert_eq!(hint_list.size(), 2);
let expected_hints = "/*+ SeqScan(title_basics)\nIndexScan(title_ratings idx_title_ratings_tconst) */";
assert_eq!(hint_list.to_string(), expected_hints);
// let hint = PgHint::IndexScan {
// table: "title_basics".to_string(),
// index: Some("idx_title_basics_tconst".to_string()),
// };
// assert_eq!(
// hint.to_string(),
// "IndexScan(title_basics idx_title_basics_tconst)"
// );
// let hint = PgHint::NoSeqScan {
// table: "title_basics".to_string(),
// };
// assert_eq!(hint.to_string(), "NoSeqScan(title_basics)");
// let hint = PgHint::NoIndexScan {
// table: "title_basics".to_string(),
// };
// assert_eq!(hint.to_string(), "NoIndexScan(title_basics)");
// let hint = PgHint::NoIndexOnlyScan {
// table: "title_basics".to_string(),
// };
// assert_eq!(hint.to_string(), "NoIndexOnlyScan(title_basics)");
// let hint = PgHint::JoinOrder {
// join_order: "title_basics, title_ratings".to_string(),
// };
// assert_eq!(hint.to_string(), "Leading(title_basics, title_ratings)");
let tree = JoinNode::Internal(InternalNode {
inner: Box::new(JoinNode::Leaf(LeafNode::new(
"title_basics".to_string(),
))),
outer: Box::new(JoinNode::Leaf(LeafNode::new(
"title_ratings".to_string(),
))),
join_algorithm: JoinAlgorithm::HashJoin,
join_card: None,
memoize: None,
});
let join_method_only_config = HintEngineConfig::new()
.with_hint_type(PGHintType::JoinMethod)
.build();
let hint_list =
PgHintList::from_join_tree(&tree, join_method_only_config).unwrap();
assert_eq!(hint_list.size(), 1);
assert_eq!(
hint_list.to_string(),
"/*+ HashJoin(title_basics title_ratings) */"
);
let join_order_and_method_config = HintEngineConfig::new()
.with_hint_type(PGHintType::JoinOrder)
.with_hint_type(PGHintType::JoinMethod)
.build();
let hint_list =
PgHintList::from_join_tree(&tree, join_order_and_method_config)
.unwrap();
assert_eq!(hint_list.size(), 2);
assert_eq!(
hint_list.to_string(),
"/*+ Leading(title_basics title_ratings)\nHashJoin(title_basics title_ratings) */"
);
let three_join_tree = JoinNode::Internal(InternalNode {
inner: Box::new(tree.clone()),
outer: Box::new(JoinNode::Leaf(LeafNode::new(
"title_principals".to_string(),
))),
join_algorithm: JoinAlgorithm::HashJoin,
join_card: None,
memoize: None,
}); // ((A B) C)
// Test with inner/outer preservation
let join_order_inner_outer_config = HintEngineConfig::new()
.with_hint_type(PGHintType::JoinOrderInnerOuter)
.build();
let hint_list = PgHintList::from_join_tree(
&three_join_tree,
join_order_inner_outer_config,
)
.unwrap();
// TODO(bobby) clean up white space, but doesn't affect functionality
assert_eq!(hint_list.size(), 1);
assert_eq!(
hint_list.to_string().replace(" ", ""),
"/*+ Leading(((title_basics title_ratings) title_principals)) */"
.replace(" ", "")
);
// Test table display with alias for join and scan method hints
let alias_tree = JoinNode::Internal(InternalNode {
inner: Box::new(JoinNode::Leaf(
LeafNode::new("title_basics".to_string())
.with_alias("tb".to_string())
.with_scan_method(ScanMethod::SeqScan),
)),
outer: Box::new(JoinNode::Leaf(
LeafNode::new("title_ratings".to_string())
.with_alias("tr".to_string())
.with_scan_method(ScanMethod::Index(
"idx_title_ratings_tconst".to_string(),
)),
)),
join_algorithm: JoinAlgorithm::HashJoin,
join_card: None,
memoize: None,
});
println!("Alias Tree: {:?}", alias_tree);
let scan_config = HintEngineConfig::new()
.with_hint_type(PGHintType::ScanMethod)
.build();
let hint_list =
PgHintList::from_join_tree(&alias_tree, scan_config).unwrap();
assert_eq!(hint_list.size(), 2);
println!("Hint List: {:?}", hint_list);
let expected_hints =
"/*+ SeqScan(tb)\nIndexScan(tr idx_title_ratings_tconst) */";
assert_eq!(
hint_list.to_string().replace(" ", ""),
expected_hints.replace(" ", "")
);
let join_config = HintEngineConfig::new()
.with_hint_type(PGHintType::JoinMethod)
.build();
let hint_list =
PgHintList::from_join_tree(&alias_tree, join_config).unwrap();
assert_eq!(hint_list.size(), 1);
assert_eq!(
hint_list.to_string().replace(" ", ""),
"/*+ HashJoin(tb tr) */".replace(" ", "")
);
// "title_ratings".to_string(),
// ],
// };
// assert_eq!(hint.to_string(), "MergeJoin(title_basics, title_ratings)");
// let hint = PgHint::IndexOnlyScan {
// table: "title_basics".to_string(),
// };
// assert_eq!(hint.to_string(), "IndexOnlyScan(title_basics)");
// let hint = PgHint::ValueScan {
// table: "title_basics".to_string(),
// };
// assert_eq!(hint.to_string(), "ValueScan(title_basics)");
// let hint = PgHint::SubqueryScan {
// table: "title_basics".to_string(),
// };
// assert_eq!(hint.to_string(), "SubqueryScan(title_basics)");
}
// #[test]
// fn test_hint_list_display() {
// let config = HintEngineConfig::new()
// .with_hint_type(PGHintType::ScanMethod)
// .build();
// let mut hint_list = PgHintList::new(config);
// hint_list.add_hint(PgHint::SeqScan {
// table: "title_basics".to_string(),
// });
// hint_list.add_hint(PgHint::IndexScan {
// table: "title_basics".to_string(),
// index: Some("idx_title_basics_tconst".to_string()),
// });
// assert_eq!(
// hint_list.to_string(),
// "/*+ SeqScan(title_basics) IndexScan(title_basics idx_title_basics_tconst) */"
// );
// }
#[test]
fn user_specified_negative_hints() {
// Create a simple join tree: t1 join t2
let tree = JoinNode::Internal(InternalNode {
inner: Box::new(JoinNode::Leaf(
LeafNode::new("t1".into())
.with_scan_method(ScanMethod::NoSeqScan),
)),
outer: Box::new(JoinNode::Leaf(
LeafNode::new("t2".into())
.with_scan_method(ScanMethod::NoIndexScan),
)),
join_algorithm: JoinAlgorithm::NoNestedLoopJoin,
join_card: None,
memoize: None,
});
let cfg = HintEngineConfig::new()
.with_hint_type(PGHintType::ScanMethod)
.with_hint_type(PGHintType::JoinMethod)
.build();
let hints = PgHintList::from_join_tree(&tree, cfg).unwrap().to_string();
eprintln!("{}", hints);
assert!(hints.contains("NoSeqScan(t1)"));
assert!(hints.contains("NoIndexScan(t2)"));
assert!(hints.contains("NoNestLoop(t1 t2)"));
}
#[test]
fn test_parallel_hints() {
use crate::hint_engine::{
InternalNode, JoinAlgorithm, JoinNode, LeafNode, ParallelHint,
engine::HintEngineConfig,
};
// Create a simple join tree: t1 join t2
let tree = JoinNode::Internal(InternalNode {
inner: Box::new(JoinNode::Leaf(
LeafNode::new("t1".into()).with_parallel_hint(ParallelHint {
workers: 8,
mode: None,
}),
)),
outer: Box::new(JoinNode::Leaf(
LeafNode::new("t2".into()).with_parallel_hint(ParallelHint {
workers: 0,
mode: Some(crate::hint_engine::ParallelMode::Hard),
}),
)),
join_algorithm: JoinAlgorithm::HashJoin,
join_card: None,
memoize: None,
});
let cfg = HintEngineConfig::new()
.with_hint_type(PGHintType::Parallel)
.build();
let hints = PgHintList::from_join_tree(&tree, cfg).unwrap().to_string();
eprintln!("Generated Hints:\n{}", hints);
assert!(hints.contains("Parallel(t1 8)"));
assert!(hints.contains("Parallel(t2 0 hard)"));
}
#[test]
fn user_specified_memoize_hints() {
use crate::hint_engine::{
InternalNode, JoinAlgorithm, JoinNode, LeafNode,
engine::HintEngineConfig,
};
// Create a simple join tree: t1 join t2
let tree = JoinNode::Internal(InternalNode {
inner: Box::new(JoinNode::Leaf(LeafNode::new("t1".into()))),
outer: Box::new(JoinNode::Leaf(LeafNode::new("t2".into()))),
join_algorithm: JoinAlgorithm::HashJoin,
join_card: None,
memoize: Some(true),
});
let cfg = HintEngineConfig::new()
.with_hint_type(PGHintType::JoinMemoize)
.build();
let hints = PgHintList::from_join_tree(&tree, cfg).unwrap().to_string();
assert!(hints.contains("Memoize(t1 t2)"));
}
#[test]
fn user_specified_guc_param_hints() {
use crate::hint_engine::{
InternalNode, JoinAlgorithm, JoinNode, LeafNode,
engine::HintEngineConfig,
};
let tree = JoinNode::Internal(InternalNode {
inner: Box::new(JoinNode::Leaf(LeafNode::new("t1".into()))),
outer: Box::new(JoinNode::Leaf(LeafNode::new("t2".into()))),
join_algorithm: JoinAlgorithm::HashJoin,
join_card: None,
memoize: None,
});
let cfg = HintEngineConfig::new()
.with_hint_type(PGHintType::GucParameter)
.build();
let mut hints = PgHintList::from_join_tree(&tree, cfg).unwrap();
hints.add_hint(PgHint::Set {
param: GucParam {
parameter: "random_page_cost".to_string(),
value: "1.0".to_string(),
},
});
hints.add_hint(PgHint::Set {
param: GucParam {
parameter: "work_mem".to_string(),
value: "'256MB'".to_string(),
},
});
hints.add_hint(PgHint::Set {
param: GucParam {
parameter: "enable_hashjoin".to_string(),
value: "off".to_string(),
},
});
let hints = hints.to_string();
assert!(hints.contains("Set(random_page_cost 1.0)"));
assert!(hints.contains("Set(work_mem '256MB')"));
assert!(hints.contains("Set(enable_hashjoin off)"));
}
// #[test]
// fn user_specified_regex_index_hints() {
// use crate::hint_engine::{
// IndexPattern, InternalNode, JoinAlgorithm, JoinNode, LeafNode,
// engine::HintEngineConfig,
// };
// // Create a three-table join tree: t1 join t2 join t3
// let tree = JoinNode::Internal(InternalNode {
// inner: Box::new(JoinNode::Internal(InternalNode {
// inner: Box::new(JoinNode::Leaf(LeafNode::new("t1".into()))),
// outer: Box::new(JoinNode::Leaf(LeafNode::new("t2".into()))),
// join_algorithm: JoinAlgorithm::HashJoin,
// join_card: None,
// })),
// outer: Box::new(JoinNode::Leaf(LeafNode::new("t3".into()))),
// join_algorithm: JoinAlgorithm::HashJoin,
// join_card: None,
// });
// let cfg = HintEngineConfig::new()
// .with_hint_type(PGHintType::RegexScan)
// .with_index_scan_regexp_hint(
// "t1",
// IndexPattern::Regex("^idx_.*_id$".into()),