-
Notifications
You must be signed in to change notification settings - Fork 397
Expand file tree
/
Copy pathTiDBProvider.java
More file actions
263 lines (234 loc) · 10.4 KB
/
TiDBProvider.java
File metadata and controls
263 lines (234 loc) · 10.4 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
package sqlancer.tidb;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;
import com.google.auto.service.AutoService;
import sqlancer.AbstractAction;
import sqlancer.DatabaseProvider;
import sqlancer.IgnoreMeException;
import sqlancer.MainOptions;
import sqlancer.Randomly;
import sqlancer.SQLConnection;
import sqlancer.SQLGlobalState;
import sqlancer.SQLProviderAdapter;
import sqlancer.StatementExecutor;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.common.query.SQLQueryProvider;
import sqlancer.common.query.SQLancerResultSet;
import sqlancer.tidb.TiDBProvider.TiDBGlobalState;
import sqlancer.tidb.TiDBSchema.TiDBTable;
import sqlancer.tidb.gen.TiDBAlterTableGenerator;
import sqlancer.tidb.gen.TiDBAnalyzeTableGenerator;
import sqlancer.tidb.gen.TiDBDeleteGenerator;
import sqlancer.tidb.gen.TiDBDropTableGenerator;
import sqlancer.tidb.gen.TiDBDropViewGenerator;
import sqlancer.tidb.gen.TiDBIndexGenerator;
import sqlancer.tidb.gen.TiDBInsertGenerator;
import sqlancer.tidb.gen.TiDBSetGenerator;
import sqlancer.tidb.gen.TiDBTableGenerator;
import sqlancer.tidb.gen.TiDBUpdateGenerator;
import sqlancer.tidb.gen.TiDBViewGenerator;
@AutoService(DatabaseProvider.class)
public class TiDBProvider extends SQLProviderAdapter<TiDBGlobalState, TiDBOptions> {
public TiDBProvider() {
super(TiDBGlobalState.class, TiDBOptions.class);
}
public enum Action implements AbstractAction<TiDBGlobalState> {
CREATE_TABLE(TiDBTableGenerator::createRandomTableStatement), // 0
CREATE_INDEX(TiDBIndexGenerator::getQuery), // 1
VIEW_GENERATOR(TiDBViewGenerator::getQuery), // 2
INSERT(TiDBInsertGenerator::getQuery), // 3
ALTER_TABLE(TiDBAlterTableGenerator::getQuery), // 4
TRUNCATE((g) -> new SQLQueryAdapter("TRUNCATE " + g.getSchema().getRandomTable(t -> !t.isView()).getName())), // 5
UPDATE(TiDBUpdateGenerator::getQuery), // 6
DELETE(TiDBDeleteGenerator::getQuery), // 7
SET(TiDBSetGenerator::getQuery), // 8
ADMIN_CHECKSUM_TABLE(
(g) -> new SQLQueryAdapter("ADMIN CHECKSUM TABLE " + g.getSchema().getRandomTable().getName())), // 9
ANALYZE_TABLE(TiDBAnalyzeTableGenerator::getQuery), // 10
DROP_TABLE(TiDBDropTableGenerator::dropTable), // 11
DROP_VIEW(TiDBDropViewGenerator::dropView); // 12
private final SQLQueryProvider<TiDBGlobalState> sqlQueryProvider;
Action(SQLQueryProvider<TiDBGlobalState> sqlQueryProvider) {
this.sqlQueryProvider = sqlQueryProvider;
}
@Override
public SQLQueryAdapter getQuery(TiDBGlobalState state) throws Exception {
return sqlQueryProvider.getQuery(state);
}
}
public static class TiDBGlobalState extends SQLGlobalState<TiDBOptions, TiDBSchema> {
@Override
protected TiDBSchema readSchema() throws SQLException {
return TiDBSchema.fromConnection(getConnection(), getDatabaseName());
}
}
private static int mapActions(TiDBGlobalState globalState, Action a) {
Randomly r = globalState.getRandomly();
switch (a) {
case ANALYZE_TABLE:
case CREATE_INDEX:
return r.getInteger(0, 2);
case INSERT:
return r.getInteger(0, globalState.getOptions().getMaxNumberInserts());
case TRUNCATE:
case DELETE:
case ADMIN_CHECKSUM_TABLE:
return r.getInteger(0, 2);
case SET:
case UPDATE:
return r.getInteger(0, 5);
case VIEW_GENERATOR:
// https://github.com/tidb-challenge-program/bug-hunting-issue/issues/8
return r.getInteger(0, 2);
case ALTER_TABLE:
return r.getInteger(0, 10); // https://github.com/tidb-challenge-program/bug-hunting-issue/issues/10
case CREATE_TABLE:
case DROP_TABLE:
case DROP_VIEW:
return 0;
default:
throw new AssertionError(a);
}
}
@Override
public void generateDatabase(TiDBGlobalState globalState) throws Exception {
for (int i = 0; i < Randomly.fromOptions(1, 2); i++) {
boolean success;
do {
SQLQueryAdapter qt = new TiDBTableGenerator().getQuery(globalState);
success = globalState.executeStatement(qt);
} while (!success);
}
StatementExecutor<TiDBGlobalState, Action> se = new StatementExecutor<>(globalState, Action.values(),
TiDBProvider::mapActions, (q) -> {
if (globalState.getSchema().getDatabaseTables().isEmpty()) {
throw new IgnoreMeException();
}
});
try {
se.executeStatements();
} catch (SQLException e) {
if (e.getMessage().contains(
"references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them")) {
throw new IgnoreMeException(); // TODO: drop view instead
} else {
throw new AssertionError(e);
}
}
if (globalState.getDbmsSpecificOptions().getTestOracleFactory().stream()
.anyMatch((o) -> o == TiDBOracleFactory.CERT)) {
// Disable strict Group By constraints for ROW oracle
globalState.executeStatement(new SQLQueryAdapter(
"SET @@sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';"));
// Enfore statistic collected for all tables
ExpectedErrors errors = new ExpectedErrors();
TiDBErrors.addExpressionErrors(errors);
for (TiDBTable table : globalState.getSchema().getDatabaseTables()) {
if (!table.isView()) {
globalState.executeStatement(new SQLQueryAdapter("ANALYZE TABLE " + table.getName() + ";", errors));
}
}
}
// TiFlash replication settings
if (globalState.getDbmsSpecificOptions().tiflash) {
ExpectedErrors errors = new ExpectedErrors();
TiDBErrors.addExpressionErrors(errors);
for (TiDBTable table : globalState.getSchema().getDatabaseTables()) {
if (!table.isView()) {
globalState.executeStatement(
new SQLQueryAdapter("ALTER TABLE " + table.getName() + " SET TIFLASH REPLICA 1;", errors));
}
}
if (Randomly.getBoolean()) {
globalState.executeStatement(new SQLQueryAdapter("set @@tidb_enforce_mpp=1;"));
}
}
}
@Override
public SQLConnection createDatabase(TiDBGlobalState globalState) throws SQLException {
String host = globalState.getOptions().getHost();
int port = globalState.getOptions().getPort();
if (host == null) {
host = TiDBOptions.DEFAULT_HOST;
}
if (port == MainOptions.NO_SET_PORT) {
port = TiDBOptions.DEFAULT_PORT;
}
String databaseName = globalState.getDatabaseName();
String url = String.format("jdbc:mysql://%s:%d/", host, port);
Connection con = DriverManager.getConnection(url, globalState.getOptions().getUserName(),
globalState.getOptions().getPassword());
globalState.getState().logStatement("USE test");
globalState.getState().logStatement("DROP DATABASE IF EXISTS " + databaseName);
String createDatabaseCommand = "CREATE DATABASE " + databaseName;
globalState.getState().logStatement(createDatabaseCommand);
globalState.getState().logStatement("USE " + databaseName);
try (Statement s = con.createStatement()) {
s.execute("DROP DATABASE IF EXISTS " + databaseName);
if (globalState.getDbmsSpecificOptions().nonPreparePlanCache) {
s.execute("set global tidb_enable_non_prepared_plan_cache=ON;");
}
}
try (Statement s = con.createStatement()) {
s.execute(createDatabaseCommand);
}
con.close();
con = DriverManager.getConnection(url + databaseName, globalState.getOptions().getUserName(),
globalState.getOptions().getPassword());
return new SQLConnection(con);
}
@Override
public String getDBMSName() {
return "tidb";
}
@Override
public String getQueryPlan(String selectStr, TiDBGlobalState globalState) throws Exception {
String queryPlan = "";
if (globalState.getOptions().logEachSelect()) {
globalState.getLogger().writeCurrent(selectStr);
try {
globalState.getLogger().getCurrentFileWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
SQLQueryAdapter q = new SQLQueryAdapter("EXPLAIN FORMAT=brief " + selectStr);
try (SQLancerResultSet rs = q.executeAndGet(globalState)) {
if (rs != null) {
while (rs.next()) {
String targetQueryPlan = rs.getString(1).replace("├─", "").replace("└─", "").replace("│", "").trim()
+ ";"; // Unify format
queryPlan += targetQueryPlan;
}
}
} catch (Throwable e) {
e.printStackTrace();
}
return queryPlan;
}
@Override
protected double[] initializeWeightedAverageReward() {
return new double[Action.values().length];
}
@Override
protected void executeMutator(int index, TiDBGlobalState globalState) throws Exception {
SQLQueryAdapter queryMutateTable = Action.values()[index].getQuery(globalState);
globalState.executeStatement(queryMutateTable);
}
@Override
public boolean addRowsToAllTables(TiDBGlobalState globalState) throws Exception {
List<TiDBTable> tablesNoRow = globalState.getSchema().getDatabaseTables().stream()
.filter(t -> t.getNrRows(globalState) == 0).collect(Collectors.toList());
for (TiDBTable table : tablesNoRow) {
SQLQueryAdapter queryAddRows = TiDBInsertGenerator.getQuery(globalState, table);
globalState.executeStatement(queryAddRows);
}
return true;
}
}