-
Notifications
You must be signed in to change notification settings - Fork 397
Expand file tree
/
Copy pathCockroachDBProvider.java
More file actions
365 lines (337 loc) · 16.4 KB
/
CockroachDBProvider.java
File metadata and controls
365 lines (337 loc) · 16.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
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
package sqlancer.cockroachdb;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.google.auto.service.AutoService;
import sqlancer.DatabaseProvider;
import sqlancer.IgnoreMeException;
import sqlancer.Main.QueryManager;
import sqlancer.MainOptions;
import sqlancer.Randomly;
import sqlancer.SQLConnection;
import sqlancer.SQLGlobalState;
import sqlancer.SQLProviderAdapter;
import sqlancer.cockroachdb.CockroachDBProvider.CockroachDBGlobalState;
import sqlancer.cockroachdb.CockroachDBSchema.CockroachDBTable;
import sqlancer.cockroachdb.gen.CockroachDBCommentOnGenerator;
import sqlancer.cockroachdb.gen.CockroachDBCreateStatisticsGenerator;
import sqlancer.cockroachdb.gen.CockroachDBDeleteGenerator;
import sqlancer.cockroachdb.gen.CockroachDBDropTableGenerator;
import sqlancer.cockroachdb.gen.CockroachDBDropViewGenerator;
import sqlancer.cockroachdb.gen.CockroachDBIndexGenerator;
import sqlancer.cockroachdb.gen.CockroachDBInsertGenerator;
import sqlancer.cockroachdb.gen.CockroachDBRandomQuerySynthesizer;
import sqlancer.cockroachdb.gen.CockroachDBSetClusterSettingGenerator;
import sqlancer.cockroachdb.gen.CockroachDBSetSessionGenerator;
import sqlancer.cockroachdb.gen.CockroachDBShowGenerator;
import sqlancer.cockroachdb.gen.CockroachDBTableGenerator;
import sqlancer.cockroachdb.gen.CockroachDBTruncateGenerator;
import sqlancer.cockroachdb.gen.CockroachDBUpdateGenerator;
import sqlancer.cockroachdb.gen.CockroachDBViewGenerator;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.common.query.SQLQueryProvider;
import sqlancer.common.query.SQLancerResultSet;
@AutoService(DatabaseProvider.class)
public class CockroachDBProvider extends SQLProviderAdapter<CockroachDBGlobalState, CockroachDBOptions> {
public CockroachDBProvider() {
super(CockroachDBGlobalState.class, CockroachDBOptions.class);
}
public enum Action {
CREATE_TABLE(CockroachDBTableGenerator::generate), CREATE_INDEX(CockroachDBIndexGenerator::create), //
CREATE_VIEW(CockroachDBViewGenerator::generate), //
CREATE_STATISTICS(CockroachDBCreateStatisticsGenerator::create), //
INSERT(CockroachDBInsertGenerator::insert), //
UPDATE(CockroachDBUpdateGenerator::gen), //
SET_SESSION(CockroachDBSetSessionGenerator::create), //
SET_CLUSTER_SETTING(CockroachDBSetClusterSettingGenerator::create), //
DELETE(CockroachDBDeleteGenerator::delete), //
TRUNCATE(CockroachDBTruncateGenerator::truncate), //
DROP_TABLE(CockroachDBDropTableGenerator::drop), //
DROP_VIEW(CockroachDBDropViewGenerator::drop), //
COMMENT_ON(CockroachDBCommentOnGenerator::comment), //
SHOW(CockroachDBShowGenerator::show), //
TRANSACTION((g) -> {
String s = Randomly.fromOptions("BEGIN", "ROLLBACK", "COMMIT");
return new SQLQueryAdapter(s, ExpectedErrors.from("there is no transaction in progress",
"there is already a transaction in progress", "current transaction is aborted"));
}), EXPLAIN((g) -> {
StringBuilder sb = new StringBuilder("EXPLAIN ");
ExpectedErrors errors = new ExpectedErrors();
if (Randomly.getBoolean()) {
sb.append("(");
sb.append(Randomly.fromOptions("VERBOSE", "TYPES", "OPT", "DISTSQL", "VEC"));
sb.append(") ");
errors.add("cannot set EXPLAIN mode more than once");
errors.add("unable to vectorize execution plan");
errors.add("unsupported type");
errors.add("vectorize is set to 'off'");
}
sb.append(CockroachDBRandomQuerySynthesizer.generate(g, Randomly.smallNumber() + 1));
CockroachDBErrors.addExpressionErrors(errors);
return new SQLQueryAdapter(sb.toString(), errors);
}), //
SCRUB((g) -> new SQLQueryAdapter(
"EXPERIMENTAL SCRUB table " + g.getSchema().getRandomTable(t -> !t.isView()).getName(),
// https://github.com/cockroachdb/cockroach/issues/46401
ExpectedErrors.from("scrub-fk: column \"t.rowid\" does not exist",
"check-constraint: cannot access temporary tables of other sessions" /*
* https:// github. com/
* cockroachdb / cockroach
* /issues/ 47031
*/))), //
SPLIT((g) -> {
StringBuilder sb = new StringBuilder("ALTER INDEX ");
CockroachDBTable randomTable = g.getSchema().getRandomTable();
sb.append(randomTable.getName());
sb.append("@");
sb.append(randomTable.getRandomIndex());
if (Randomly.getBoolean()) {
sb.append(" SPLIT AT VALUES (true), (false);");
} else {
sb.append(" SPLIT AT VALUES (NULL);");
}
return new SQLQueryAdapter(sb.toString(), ExpectedErrors.from("must be of type"));
});
private final SQLQueryProvider<CockroachDBGlobalState> sqlQueryProvider;
Action(SQLQueryProvider<CockroachDBGlobalState> sqlQueryProvider) {
this.sqlQueryProvider = sqlQueryProvider;
}
public SQLQueryAdapter getQuery(CockroachDBGlobalState state) throws Exception {
return sqlQueryProvider.getQuery(state);
}
}
public static class CockroachDBGlobalState extends SQLGlobalState<CockroachDBOptions, CockroachDBSchema> {
@Override
protected CockroachDBSchema readSchema() throws SQLException {
return CockroachDBSchema.fromConnection(getConnection(), getDatabaseName());
}
}
@Override
public void generateDatabase(CockroachDBGlobalState globalState) throws Exception {
QueryManager<SQLConnection> manager = globalState.getManager();
MainOptions options = globalState.getOptions();
List<String> standardSettings = new ArrayList<>();
standardSettings.add("--Don't send automatic bug reports");
standardSettings.add("SET CLUSTER SETTING debug.panic_on_failed_assertions = true;");
standardSettings.add("SET CLUSTER SETTING diagnostics.reporting.enabled = false;");
standardSettings.add("SET CLUSTER SETTING diagnostics.reporting.send_crash_reports = false;");
standardSettings.add("-- Disable the collection of metrics and hope that it helps performance");
standardSettings.add("SET CLUSTER SETTING sql.metrics.statement_details.enabled = 'off'");
standardSettings.add("SET CLUSTER SETTING sql.metrics.statement_details.plan_collection.enabled = 'off'");
standardSettings.add("SET CLUSTER SETTING sql.stats.automatic_collection.enabled = 'off'");
standardSettings.add("SET CLUSTER SETTING timeseries.storage.enabled = 'off'");
if (globalState.getDbmsSpecificOptions().testHashIndexes) {
standardSettings.add("set experimental_enable_hash_sharded_indexes='on';");
}
if (globalState.getDbmsSpecificOptions().testTempTables) {
standardSettings.add("SET experimental_enable_temp_tables = 'on'");
}
for (String s : standardSettings) {
manager.execute(new SQLQueryAdapter(s));
}
for (int i = 0; i < Randomly.fromOptions(2, 3); i++) {
boolean success = false;
do {
try {
SQLQueryAdapter q = CockroachDBTableGenerator.generate(globalState);
success = globalState.executeStatement(q);
} catch (IgnoreMeException e) {
// continue trying
}
} while (!success);
}
int[] nrRemaining = new int[Action.values().length];
List<Action> actions = new ArrayList<>();
int total = 0;
for (int i = 0; i < Action.values().length; i++) {
Action action = Action.values()[i];
int nrPerformed = 0;
switch (action) {
case INSERT:
nrPerformed = globalState.getRandomly().getInteger(0, options.getMaxNumberInserts());
break;
case UPDATE:
case SPLIT:
nrPerformed = globalState.getRandomly().getInteger(0, 3);
break;
case EXPLAIN:
nrPerformed = globalState.getRandomly().getInteger(0, 10);
break;
case SHOW:
case TRUNCATE:
case DELETE:
case CREATE_STATISTICS:
nrPerformed = globalState.getRandomly().getInteger(0, 2);
break;
case CREATE_VIEW:
nrPerformed = globalState.getRandomly().getInteger(0, 2);
break;
case SET_SESSION:
case SET_CLUSTER_SETTING:
nrPerformed = globalState.getRandomly().getInteger(0, 3);
break;
case CREATE_INDEX:
nrPerformed = globalState.getRandomly().getInteger(0, 10);
break;
case COMMENT_ON:
case SCRUB:
nrPerformed = 0; /*
* there are a number of open SCRUB bugs, of which
* https://github.com/cockroachdb/cockroach/issues/47116 crashes the server
*/
break;
case TRANSACTION:
case CREATE_TABLE:
case DROP_TABLE:
case DROP_VIEW:
nrPerformed = 0; // r.getInteger(0, 0);
break;
default:
throw new AssertionError(action);
}
if (nrPerformed != 0) {
actions.add(action);
}
nrRemaining[action.ordinal()] = nrPerformed;
total += nrPerformed;
}
while (total != 0) {
Action nextAction = null;
int selection = globalState.getRandomly().getInteger(0, total);
int previousRange = 0;
for (int i = 0; i < nrRemaining.length; i++) {
if (previousRange <= selection && selection < previousRange + nrRemaining[i]) {
nextAction = Action.values()[i];
break;
} else {
previousRange += nrRemaining[i];
}
}
assert nextAction != null;
assert nrRemaining[nextAction.ordinal()] > 0;
nrRemaining[nextAction.ordinal()]--;
SQLQueryAdapter query = null;
try {
boolean success;
int nrTries = 0;
do {
query = nextAction.getQuery(globalState);
success = globalState.executeStatement(query);
} while (!success && nrTries++ < 1000);
} catch (IgnoreMeException e) {
}
if (query != null && query.couldAffectSchema() && globalState.getSchema().getDatabaseTables().isEmpty()) {
throw new IgnoreMeException();
}
total--;
}
if (globalState.getDbmsSpecificOptions().getTestOracleFactory().stream()
.anyMatch((o) -> o == CockroachDBOracleFactory.CERT)) {
// Enfore statistic collected for all tables
ExpectedErrors errors = new ExpectedErrors();
CockroachDBErrors.addExpressionErrors(errors);
for (CockroachDBTable table : globalState.getSchema().getDatabaseTables()) {
globalState.executeStatement(new SQLQueryAdapter("ANALYZE " + table.getName() + ";", errors));
}
}
}
@Override
public SQLConnection createDatabase(CockroachDBGlobalState globalState) throws SQLException {
String host = globalState.getOptions().getHost();
int port = globalState.getOptions().getPort();
if (host == null) {
host = CockroachDBOptions.DEFAULT_HOST;
}
if (port == MainOptions.NO_SET_PORT) {
port = CockroachDBOptions.DEFAULT_PORT;
}
String databaseName = globalState.getDatabaseName();
String url = String.format("jdbc:postgresql://%s:%d/test", 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 + " CASCADE");
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);
}
try (Statement s = con.createStatement()) {
s.execute(createDatabaseCommand);
}
con.close();
con = DriverManager.getConnection(String.format("jdbc:postgresql://%s:%d/%s", host, port, databaseName),
globalState.getOptions().getUserName(), globalState.getOptions().getPassword());
return new SQLConnection(con);
}
@Override
public String getDBMSName() {
return "cockroachdb";
}
@Override
public String getQueryPlan(String selectStr, CockroachDBGlobalState globalState) throws Exception {
String queryPlan = "";
String explainQuery = "EXPLAIN (OPT) " + selectStr;
if (globalState.getOptions().logEachSelect()) {
globalState.getLogger().writeCurrent(explainQuery);
try {
globalState.getLogger().getCurrentFileWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
SQLQueryAdapter q = new SQLQueryAdapter(explainQuery);
boolean afterProjection = false; // Remove the concrete expression after each Projection operator
try (SQLancerResultSet rs = q.executeAndGet(globalState)) {
if (rs != null) {
while (rs.next()) {
String targetQueryPlan = rs.getString(1).replace("└──", "").replace("├──", "").replace("│", "")
.trim() + ";"; // Unify format
if (afterProjection) {
afterProjection = false;
continue;
}
if (targetQueryPlan.startsWith("projections")) {
afterProjection = true;
}
// Remove all concrete expressions by keywords
if (targetQueryPlan.contains(">") || targetQueryPlan.contains("<") || targetQueryPlan.contains("=")
|| targetQueryPlan.contains("*") || targetQueryPlan.contains("+")
|| targetQueryPlan.contains("'")) {
continue;
}
queryPlan += targetQueryPlan;
}
}
} catch (AssertionError e) {
throw new AssertionError("Explain failed: " + explainQuery);
}
return queryPlan;
}
@Override
protected double[] initializeWeightedAverageReward() {
return new double[Action.values().length];
}
@Override
protected void executeMutator(int index, CockroachDBGlobalState globalState) throws Exception {
SQLQueryAdapter queryMutateTable = Action.values()[index].getQuery(globalState);
globalState.executeStatement(queryMutateTable);
}
@Override
public boolean addRowsToAllTables(CockroachDBGlobalState globalState) throws Exception {
List<CockroachDBTable> tablesNoRow = globalState.getSchema().getDatabaseTables().stream()
.filter(t -> t.getNrRows(globalState) == 0).collect(Collectors.toList());
for (CockroachDBTable table : tablesNoRow) {
SQLQueryAdapter queryAddRows = CockroachDBInsertGenerator.insert(globalState, table);
globalState.executeStatement(queryAddRows);
}
return true;
}
}