-
Notifications
You must be signed in to change notification settings - Fork 398
Expand file tree
/
Copy pathMongoDBInsertQuery.java
More file actions
87 lines (76 loc) · 2.81 KB
/
MongoDBInsertQuery.java
File metadata and controls
87 lines (76 loc) · 2.81 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
package sqlancer.mongodb.query;
import org.bson.BsonDateTime;
import org.bson.BsonTimestamp;
import org.bson.Document;
import org.bson.types.ObjectId;
import com.mongodb.client.result.InsertOneResult;
import sqlancer.GlobalState;
import sqlancer.Main;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.mongodb.MongoDBConnection;
import sqlancer.mongodb.MongoDBQueryAdapter;
import sqlancer.mongodb.MongoDBSchema.MongoDBTable;
public class MongoDBInsertQuery extends MongoDBQueryAdapter {
boolean excluded;
private final MongoDBTable table;
private final Document documentToBeInserted;
public MongoDBInsertQuery(MongoDBTable table, Document documentToBeInserted) {
this.table = table;
this.documentToBeInserted = documentToBeInserted;
this.excluded = false;
}
@Override
public String getLogString() {
StringBuilder sb = new StringBuilder();
sb.append("db." + table.getName() + ".insert({");
String helper = "";
for (String key : documentToBeInserted.keySet()) {
sb.append(helper);
helper = ", ";
if (documentToBeInserted.get(key) instanceof ObjectId) {
continue;
}
Object value = documentToBeInserted.get(key);
sb.append(key);
sb.append(": ");
sb.append(getStringRepresentation(value));
}
sb.append("})\n");
return sb.toString();
}
private String getStringRepresentation(Object value) {
if (value instanceof Double) {
return String.valueOf(value);
} else if (value instanceof Integer) {
return "NumberInt(" + value + ")";
} else if (value instanceof String) {
return "\"" + value + "\"";
} else if (value instanceof BsonDateTime) {
return "new Date(" + ((BsonDateTime) value).getValue() + ")";
} else if (value instanceof BsonTimestamp) {
return "Timestamp(" + ((BsonTimestamp) value).getValue() + ",1)";
} else if (value instanceof Boolean) {
return String.valueOf(value);
} else if (value == null) {
return "null";
} else {
throw new IllegalStateException();
}
}
@Override
public boolean couldAffectSchema() {
return true;
}
@Override
public <G extends GlobalState<?, ?, MongoDBConnection>> boolean execute(G globalState, String... fills)
throws Exception {
Main.nrSuccessfulActions.addAndGet(1);
InsertOneResult result = globalState.getConnection().getDatabase().getCollection(table.getName())
.insertOne(documentToBeInserted);
return result.wasAcknowledged();
}
@Override
public ExpectedErrors getExpectedErrors() {
return new ExpectedErrors();
}
}