-
Notifications
You must be signed in to change notification settings - Fork 397
Expand file tree
/
Copy pathMySQLSchema.java
More file actions
299 lines (252 loc) · 10.9 KB
/
MySQLSchema.java
File metadata and controls
299 lines (252 loc) · 10.9 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
package sqlancer.mysql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import sqlancer.Randomly;
import sqlancer.SQLConnection;
import sqlancer.common.schema.AbstractRelationalTable;
import sqlancer.common.schema.AbstractRowValue;
import sqlancer.common.schema.AbstractSchema;
import sqlancer.common.schema.AbstractTableColumn;
import sqlancer.common.schema.AbstractTables;
import sqlancer.common.schema.TableIndex;
import sqlancer.mysql.MySQLSchema.MySQLTable;
import sqlancer.mysql.MySQLSchema.MySQLTable.MySQLEngine;
import sqlancer.mysql.ast.MySQLConstant;
public class MySQLSchema extends AbstractSchema<MySQLGlobalState, MySQLTable> {
private static final int NR_SCHEMA_READ_TRIES = 10;
public enum MySQLDataType {
INT, VARCHAR, FLOAT, DOUBLE, DECIMAL;
public static MySQLDataType getRandom(MySQLGlobalState globalState) {
if (globalState.usesPQS()) {
return Randomly.fromOptions(MySQLDataType.INT, MySQLDataType.VARCHAR);
} else {
return Randomly.fromOptions(values());
}
}
public boolean isNumeric() {
switch (this) {
case INT:
case DOUBLE:
case FLOAT:
case DECIMAL:
return true;
case VARCHAR:
return false;
default:
throw new AssertionError(this);
}
}
}
public static class MySQLColumn extends AbstractTableColumn<MySQLTable, MySQLDataType> {
private final boolean isPrimaryKey;
private final int precision;
public enum CollateSequence {
NOCASE, RTRIM, BINARY;
public static CollateSequence random() {
return Randomly.fromOptions(values());
}
}
public MySQLColumn(String name, MySQLDataType columnType, boolean isPrimaryKey, int precision) {
super(name, null, columnType);
this.isPrimaryKey = isPrimaryKey;
this.precision = precision;
}
public int getPrecision() {
return precision;
}
public boolean isPrimaryKey() {
return isPrimaryKey;
}
}
public static class MySQLTables extends AbstractTables<MySQLTable, MySQLColumn> {
public MySQLTables(List<MySQLTable> tables) {
super(tables);
}
public MySQLRowValue getRandomRowValue(SQLConnection con) throws SQLException {
String randomRow = String.format("SELECT %s FROM %s ORDER BY RAND() LIMIT 1", columnNamesAsString(
c -> c.getTable().getName() + "." + c.getName() + " AS " + c.getTable().getName() + c.getName()),
// columnNamesAsString(c -> "typeof(" + c.getTable().getName() + "." +
// c.getName() + ")")
tableNamesAsString());
Map<MySQLColumn, MySQLConstant> values = new HashMap<>();
try (Statement s = con.createStatement()) {
ResultSet randomRowValues = s.executeQuery(randomRow);
if (!randomRowValues.next()) {
throw new AssertionError("could not find random row! " + randomRow + "\n");
}
for (int i = 0; i < getColumns().size(); i++) {
MySQLColumn column = getColumns().get(i);
Object value;
int columnIndex = randomRowValues.findColumn(column.getTable().getName() + column.getName());
assert columnIndex == i + 1;
MySQLConstant constant;
if (randomRowValues.getString(columnIndex) == null) {
constant = MySQLConstant.createNullConstant();
} else {
switch (column.getType()) {
case INT:
value = randomRowValues.getLong(columnIndex);
constant = MySQLConstant.createIntConstant((long) value);
break;
case VARCHAR:
value = randomRowValues.getString(columnIndex);
constant = MySQLConstant.createStringConstant((String) value);
break;
default:
throw new AssertionError(column.getType());
}
}
values.put(column, constant);
}
assert !randomRowValues.next();
return new MySQLRowValue(this, values);
}
}
}
private static MySQLDataType getColumnType(String typeString) {
switch (typeString) {
case "tinyint":
case "smallint":
case "mediumint":
case "int":
case "bigint":
return MySQLDataType.INT;
case "varchar":
case "tinytext":
case "mediumtext":
case "text":
case "longtext":
return MySQLDataType.VARCHAR;
case "double":
return MySQLDataType.DOUBLE;
case "float":
return MySQLDataType.FLOAT;
case "decimal":
return MySQLDataType.DECIMAL;
default:
throw new AssertionError(typeString);
}
}
public static class MySQLRowValue extends AbstractRowValue<MySQLTables, MySQLColumn, MySQLConstant> {
MySQLRowValue(MySQLTables tables, Map<MySQLColumn, MySQLConstant> values) {
super(tables, values);
}
}
public static class MySQLTable extends AbstractRelationalTable<MySQLColumn, MySQLIndex, MySQLGlobalState> {
public enum MySQLEngine {
INNO_DB("InnoDB"), MY_ISAM("MyISAM"), MEMORY("MEMORY"), HEAP("HEAP"), CSV("CSV"), MERGE("MERGE"),
ARCHIVE("ARCHIVE"), FEDERATED("FEDERATED");
private String s;
MySQLEngine(String s) {
this.s = s;
}
public static MySQLEngine get(String val) {
return Stream.of(values()).filter(engine -> engine.s.equalsIgnoreCase(val)).findFirst().get();
}
}
private final MySQLEngine engine;
public MySQLTable(String tableName, List<MySQLColumn> columns, List<MySQLIndex> indexes, MySQLEngine engine) {
super(tableName, columns, indexes, false /* TODO: support views */);
this.engine = engine;
}
public MySQLEngine getEngine() {
return engine;
}
public boolean hasPrimaryKey() {
return getColumns().stream().anyMatch(c -> c.isPrimaryKey());
}
}
public static final class MySQLIndex extends TableIndex {
private MySQLIndex(String indexName) {
super(indexName);
}
public static MySQLIndex create(String indexName) {
return new MySQLIndex(indexName);
}
@Override
public String getIndexName() {
if (super.getIndexName().contentEquals("PRIMARY")) {
return "`PRIMARY`";
} else {
return super.getIndexName();
}
}
}
public static MySQLSchema fromConnection(SQLConnection con, String databaseName) throws SQLException {
Exception ex = null;
/* the loop is a workaround for https://bugs.mysql.com/bug.php?id=95929 */
for (int i = 0; i < NR_SCHEMA_READ_TRIES; i++) {
try {
List<MySQLTable> databaseTables = new ArrayList<>();
try (Statement s = con.createStatement()) {
try (ResultSet rs = s.executeQuery(
"select TABLE_NAME, ENGINE from information_schema.TABLES where table_schema = '"
+ databaseName + "';")) {
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME");
String tableEngineStr = rs.getString("ENGINE");
MySQLEngine engine = MySQLEngine.get(tableEngineStr);
List<MySQLColumn> databaseColumns = getTableColumns(con, tableName, databaseName);
List<MySQLIndex> indexes = getIndexes(con, tableName, databaseName);
MySQLTable t = new MySQLTable(tableName, databaseColumns, indexes, engine);
for (MySQLColumn c : databaseColumns) {
c.setTable(t);
}
databaseTables.add(t);
}
}
}
return new MySQLSchema(databaseTables);
} catch (SQLIntegrityConstraintViolationException e) {
ex = e;
}
}
throw new AssertionError(ex);
}
private static List<MySQLIndex> getIndexes(SQLConnection con, String tableName, String databaseName)
throws SQLException {
List<MySQLIndex> indexes = new ArrayList<>();
try (Statement s = con.createStatement()) {
try (ResultSet rs = s.executeQuery(String.format(
"SELECT INDEX_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME='%s';",
databaseName, tableName))) {
while (rs.next()) {
String indexName = rs.getString("INDEX_NAME");
indexes.add(MySQLIndex.create(indexName));
}
}
}
return indexes;
}
private static List<MySQLColumn> getTableColumns(SQLConnection con, String tableName, String databaseName)
throws SQLException {
List<MySQLColumn> columns = new ArrayList<>();
try (Statement s = con.createStatement()) {
try (ResultSet rs = s.executeQuery("select * from information_schema.columns where table_schema = '"
+ databaseName + "' AND TABLE_NAME='" + tableName + "'")) {
while (rs.next()) {
String columnName = rs.getString("COLUMN_NAME");
String dataType = rs.getString("DATA_TYPE");
int precision = rs.getInt("NUMERIC_PRECISION");
boolean isPrimaryKey = rs.getString("COLUMN_KEY").equals("PRI");
MySQLColumn c = new MySQLColumn(columnName, getColumnType(dataType), isPrimaryKey, precision);
columns.add(c);
}
}
}
return columns;
}
public MySQLSchema(List<MySQLTable> databaseTables) {
super(databaseTables);
}
public MySQLTables getRandomTableNonEmptyTables() {
return new MySQLTables(Randomly.nonEmptySubset(getDatabaseTables()));
}
}