forked from sqlancer/sqlancer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySQLTableGenerator.java
More file actions
384 lines (363 loc) · 14.3 KB
/
MySQLTableGenerator.java
File metadata and controls
384 lines (363 loc) · 14.3 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
package sqlancer.mysql.gen;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import sqlancer.IgnoreMeException;
import sqlancer.Randomly;
import sqlancer.common.DBMSCommon;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.mysql.MySQLBugs;
import sqlancer.mysql.MySQLGlobalState;
import sqlancer.mysql.MySQLSchema;
import sqlancer.mysql.MySQLSchema.MySQLDataType;
import sqlancer.mysql.MySQLSchema.MySQLTable.MySQLEngine;
public class MySQLTableGenerator {
private final StringBuilder sb = new StringBuilder();
private final boolean allowPrimaryKey;
private boolean setPrimaryKey;
private final String tableName;
private final Randomly r;
private boolean tableHasNullableColumn;
private MySQLEngine engine;
private int keysSpecified;
private final List<String> columns = new ArrayList<>();
private final MySQLSchema schema;
private final MySQLGlobalState globalState;
public MySQLTableGenerator(MySQLGlobalState globalState, String tableName) {
this.tableName = tableName;
this.r = globalState.getRandomly();
this.schema = globalState.getSchema();
allowPrimaryKey = Randomly.getBoolean();
this.globalState = globalState;
}
public static SQLQueryAdapter generate(MySQLGlobalState globalState, String tableName) {
return new MySQLTableGenerator(globalState, tableName).create();
}
private SQLQueryAdapter create() {
ExpectedErrors errors = new ExpectedErrors();
sb.append("CREATE");
// TODO support temporary tables in the schema
sb.append(" TABLE");
if (Randomly.getBoolean()) {
sb.append(" IF NOT EXISTS");
}
sb.append(" ");
sb.append(tableName);
if (Randomly.getBoolean() && !schema.getDatabaseTables().isEmpty()) {
sb.append(" LIKE ");
sb.append(schema.getRandomTable().getName());
return new SQLQueryAdapter(sb.toString(), true);
} else {
sb.append("(");
for (int i = 0; i < 1 + Randomly.smallNumber(); i++) {
if (i != 0) {
sb.append(", ");
}
appendColumn(i);
}
sb.append(")");
sb.append(" ");
appendTableOptions();
appendPartitionOptions();
if (engine == MySQLEngine.CSV && (tableHasNullableColumn || setPrimaryKey)) {
if (true) { // TODO
// results in an error
throw new IgnoreMeException();
}
} else if (engine == MySQLEngine.ARCHIVE && (tableHasNullableColumn || keysSpecified > 1)) {
errors.add("Too many keys specified; max 1 keys allowed");
errors.add("Table handler doesn't support NULL in given index");
addCommonErrors(errors);
return new SQLQueryAdapter(sb.toString(), errors, true);
}
addCommonErrors(errors);
return new SQLQueryAdapter(sb.toString(), errors, true);
}
}
private void addCommonErrors(ExpectedErrors list) {
list.add("The storage engine for the table doesn't support");
list.add("doesn't have this option");
list.add("must include all columns");
list.add("not allowed type for this type of partitioning");
list.add("doesn't support BLOB/TEXT columns");
list.add("A BLOB field is not allowed in partition function");
list.add("Too many keys specified; max 1 keys allowed");
list.add("The total length of the partitioning fields is too large");
list.add("Got error -1 - 'Unknown error -1' from storage engine");
}
private enum PartitionOptions {
HASH, KEY
}
private void appendPartitionOptions() {
if (engine != MySQLEngine.INNO_DB) {
return;
}
if (Randomly.getBoolean()) {
return;
}
sb.append(" PARTITION BY");
switch (Randomly.fromOptions(PartitionOptions.values())) {
case HASH:
if (Randomly.getBoolean()) {
sb.append(" LINEAR");
}
sb.append(" HASH(");
// TODO: consider arbitrary expressions
// MySQLExpression expr =
// MySQLRandomExpressionGenerator.generateRandomExpression(Collections.emptyList(),
// null, r);
// sb.append(MySQLVisitor.asString(expr));
sb.append(Randomly.fromList(columns));
sb.append(")");
break;
case KEY:
if (Randomly.getBoolean()) {
sb.append(" LINEAR");
}
sb.append(" KEY");
if (Randomly.getBoolean()) {
sb.append(" ALGORITHM=");
sb.append(Randomly.fromOptions(1, 2));
}
sb.append(" (");
sb.append(Randomly.nonEmptySubset(columns).stream().collect(Collectors.joining(", ")));
sb.append(")");
break;
default:
throw new AssertionError();
}
}
private enum TableOptions {
AUTO_INCREMENT, AVG_ROW_LENGTH, CHECKSUM, COMPRESSION, DELAY_KEY_WRITE, /* ENCRYPTION, */ ENGINE, INSERT_METHOD,
KEY_BLOCK_SIZE, MAX_ROWS, MIN_ROWS, PACK_KEYS, STATS_AUTO_RECALC, STATS_PERSISTENT, STATS_SAMPLE_PAGES;
public static List<TableOptions> getRandomTableOptions() {
List<TableOptions> options;
// try to ensure that usually, only a few of these options are generated
if (Randomly.getBooleanWithSmallProbability()) {
options = Randomly.subset(TableOptions.values());
} else {
if (Randomly.getBoolean()) {
options = Collections.emptyList();
} else {
options = Randomly.nonEmptySubset(Arrays.asList(TableOptions.values()), Randomly.smallNumber());
}
}
return options;
}
}
private void appendTableOptions() {
List<TableOptions> tableOptions = TableOptions.getRandomTableOptions();
int i = 0;
for (TableOptions o : tableOptions) {
if (i++ != 0) {
sb.append(", ");
}
switch (o) {
case AUTO_INCREMENT:
sb.append("AUTO_INCREMENT = ");
sb.append(r.getPositiveInteger());
break;
// The valid range for avg_row_length is [0,4294967295]
case AVG_ROW_LENGTH:
sb.append("AVG_ROW_LENGTH = ");
sb.append(r.getLong(0, 4294967295L + 1));
break;
case CHECKSUM:
sb.append("CHECKSUM = 1");
break;
case COMPRESSION:
sb.append("COMPRESSION = '");
sb.append(Randomly.fromOptions("ZLIB", "LZ4", "NONE"));
sb.append("'");
break;
case DELAY_KEY_WRITE:
sb.append("DELAY_KEY_WRITE = ");
sb.append(Randomly.fromOptions(0, 1));
break;
case ENGINE:
// FEDERATED: java.sql.SQLSyntaxErrorException: Unknown storage engine
// 'FEDERATED'
// "NDB": java.sql.SQLSyntaxErrorException: Unknown storage engine 'NDB'
// "EXAMPLE": java.sql.SQLSyntaxErrorException: Unknown storage engine 'EXAMPLE'
// "MERGE": java.sql.SQLException: Table 't0' is read only
String fromOptions = Randomly.fromOptions("InnoDB", "MyISAM", "MEMORY", "HEAP", "CSV", "ARCHIVE");
this.engine = MySQLEngine.get(fromOptions);
sb.append("ENGINE = ");
sb.append(fromOptions);
break;
// case ENCRYPTION:
// sb.append("ENCRYPTION = '");
// sb.append(Randomly.fromOptions("Y", "N"));
// sb.append("'");
// break;
case INSERT_METHOD:
sb.append("INSERT_METHOD = ");
sb.append(Randomly.fromOptions("NO", "FIRST", "LAST"));
break;
// The valid range for key_block_size is [0,65535]
case KEY_BLOCK_SIZE:
sb.append("KEY_BLOCK_SIZE = ");
sb.append(r.getInteger(0, 65535 + 1));
break;
case MAX_ROWS:
sb.append("MAX_ROWS = ");
sb.append(r.getLong(0, Long.MAX_VALUE));
break;
case MIN_ROWS:
sb.append("MIN_ROWS = ");
sb.append(r.getLong(1, Long.MAX_VALUE));
break;
case PACK_KEYS:
sb.append("PACK_KEYS = ");
sb.append(Randomly.fromOptions("1", "0", "DEFAULT"));
break;
case STATS_AUTO_RECALC:
sb.append("STATS_AUTO_RECALC = ");
sb.append(Randomly.fromOptions("1", "0", "DEFAULT"));
break;
case STATS_PERSISTENT:
sb.append("STATS_PERSISTENT = ");
sb.append(Randomly.fromOptions("1", "0", "DEFAULT"));
break;
case STATS_SAMPLE_PAGES:
sb.append("STATS_SAMPLE_PAGES = ");
sb.append(r.getInteger(1, Short.MAX_VALUE));
break;
default:
throw new AssertionError(o);
}
}
}
private void appendColumn(int columnId) {
String columnName = DBMSCommon.createColumnName(columnId);
columns.add(columnName);
sb.append(columnName);
appendColumnDefinition();
}
private enum ColumnOptions {
NULL_OR_NOT_NULL, UNIQUE, COMMENT, COLUMN_FORMAT, STORAGE, PRIMARY_KEY
}
private void appendColumnOption(MySQLDataType type) {
boolean isTextType = type == MySQLDataType.VARCHAR;
boolean isNull = false;
boolean columnHasPrimaryKey = false;
List<ColumnOptions> columnOptions = Randomly.subset(ColumnOptions.values());
if (!columnOptions.contains(ColumnOptions.NULL_OR_NOT_NULL)) {
tableHasNullableColumn = true;
}
if (isTextType) {
// TODO: restriction due to the limited key length
columnOptions.remove(ColumnOptions.PRIMARY_KEY);
columnOptions.remove(ColumnOptions.UNIQUE);
}
for (ColumnOptions o : columnOptions) {
sb.append(" ");
switch (o) {
case NULL_OR_NOT_NULL:
// PRIMARY KEYs cannot be NULL
if (!columnHasPrimaryKey) {
if (Randomly.getBoolean()) {
sb.append("NULL");
}
tableHasNullableColumn = true;
isNull = true;
} else {
sb.append("NOT NULL");
}
break;
case UNIQUE:
sb.append("UNIQUE");
keysSpecified++;
if (Randomly.getBoolean()) {
sb.append(" KEY");
}
break;
case COMMENT:
// TODO: generate randomly
sb.append(String.format("COMMENT '%s' ", "asdf"));
break;
case COLUMN_FORMAT:
sb.append("COLUMN_FORMAT ");
sb.append(Randomly.fromOptions("FIXED", "DYNAMIC", "DEFAULT"));
break;
case STORAGE:
sb.append("STORAGE ");
sb.append(Randomly.fromOptions("DISK", "MEMORY"));
break;
case PRIMARY_KEY:
// PRIMARY KEYs cannot be NULL
if (allowPrimaryKey && !setPrimaryKey && !isNull) {
sb.append("PRIMARY KEY");
setPrimaryKey = true;
columnHasPrimaryKey = true;
}
break;
default:
throw new AssertionError();
}
}
}
private void appendColumnDefinition() {
sb.append(" ");
MySQLDataType randomType = MySQLDataType.getRandom(globalState);
appendType(randomType);
sb.append(" ");
appendColumnOption(randomType);
}
private void appendType(MySQLDataType randomType) {
switch (randomType) {
case DECIMAL:
sb.append("DECIMAL");
optionallyAddPrecisionAndScale(sb);
break;
case INT:
sb.append(Randomly.fromOptions("TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT"));
if (Randomly.getBoolean()) {
sb.append("(");
sb.append(Randomly.getNotCachedInteger(0, 255)); // Display width out of range for column 'c0' (max =
// 255)
sb.append(")");
}
break;
case VARCHAR:
sb.append(Randomly.fromOptions("VARCHAR(500)", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT"));
break;
case FLOAT:
sb.append("FLOAT");
optionallyAddPrecisionAndScale(sb);
break;
case DOUBLE:
sb.append(Randomly.fromOptions("DOUBLE", "FLOAT"));
optionallyAddPrecisionAndScale(sb);
break;
default:
throw new AssertionError();
}
if (randomType.isNumeric()) {
if (Randomly.getBoolean() && randomType != MySQLDataType.INT && !MySQLBugs.bug99127) {
sb.append(" UNSIGNED");
}
if (!globalState.usesPQS() && Randomly.getBoolean()) {
sb.append(" ZEROFILL");
}
}
}
public static void optionallyAddPrecisionAndScale(StringBuilder sb) {
if (Randomly.getBoolean() && !MySQLBugs.bug99183) {
sb.append("(");
// The maximum number of digits (M) for DECIMAL is 65
long m = Randomly.getNotCachedInteger(1, 65);
sb.append(m);
sb.append(", ");
// The maximum number of supported decimals (D) is 30
long nCandidate = Randomly.getNotCachedInteger(1, 30);
// For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column 'c0').
long n = Math.min(nCandidate, m);
sb.append(n);
sb.append(")");
}
}
}