forked from sqlancer/sqlancer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoundDoubleConstant.java
More file actions
74 lines (58 loc) · 2.05 KB
/
RoundDoubleConstant.java
File metadata and controls
74 lines (58 loc) · 2.05 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
package sqlancer.transformations;
import java.text.DecimalFormat;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Round double values which are longer than a certain length. e.g. 2.4782565267 -> 2.478.
*
* This transformation is not based on JSQLParser.
*/
public class RoundDoubleConstant extends Transformation {
private Set<String> doubleValueCollector;
private String currentString;
private static final int ROUND_LENGTH = 3;
private DecimalFormat decimalFormat;
public RoundDoubleConstant() {
super("round double constant values");
}
@Override
public boolean init(String sql) {
super.init(sql);
decimalFormat = new DecimalFormat("#." + "#".repeat(ROUND_LENGTH));
currentString = sql;
doubleValueCollector = new HashSet<>();
String regex = "\\b-?\\d+\\.\\d+\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(sql);
while (matcher.find()) {
String matchedText = matcher.group();
String decimalPart = matchedText.replaceAll("\\d+\\.", "");
int decimalPlaces = decimalPart.length();
if (decimalPlaces > ROUND_LENGTH) {
doubleValueCollector.add(matchedText);
}
}
return true;
}
@Override
public void apply() {
for (String doubleValue : doubleValueCollector) {
double targetNumber = Double.parseDouble(doubleValue);
String roundedNumberStr = decimalFormat.format(targetNumber);
String replacement = currentString.replace(doubleValue, roundedNumberStr);
String original = currentString;
tryReplace(null, original, replacement, (p, r) -> {
currentString = r;
});
}
super.apply();
}
@Override
protected void onStatementChanged() {
if (statementChangedHandler != null) {
statementChangedHandler.accept(currentString);
}
}
}