提交 dd7cdf0d authored 作者: Thomas Mueller's avatar Thomas Mueller

Cleanup:

- Make fields and methods private where possible
- Add missing Javadocs
- Remove @throws Javadocs (all other languages don't have throws, and it doesn't help much documenting them)
- Use camel case for metaData
- Remove initializing to default values (null, 0, false) because that's anyway done automatically
- Remove @Override to let it compile with JDK 5
- Mark as 'work in progress'
上级 4c5b1c44
...@@ -38,14 +38,17 @@ import org.h2.jaqu.util.Utils; ...@@ -38,14 +38,17 @@ import org.h2.jaqu.util.Utils;
* validation. * validation.
*/ */
public class TableInspector { public class TableInspector {
String schema;
String table; private String schema;
boolean forceUpperCase; private String table;
Class<? extends java.util.Date> dateClazz; private boolean forceUpperCase;
List<String> primaryKeys = Utils.newArrayList(); private Class<? extends java.util.Date> dateClazz;
Map<String, IndexInspector> indexes; private List<String> primaryKeys = Utils.newArrayList();
Map<String, ColumnInspector> columns; private Map<String, IndexInspector> indexes;
final String eol = "\n"; private Map<String, ColumnInspector> columns;
private final String eol = "\n";
private int todoReviewWholeClass;
TableInspector(String schema, String table, boolean forceUpperCase, TableInspector(String schema, String table, boolean forceUpperCase,
Class<? extends java.util.Date> dateClazz) { Class<? extends java.util.Date> dateClazz) {
...@@ -58,36 +61,36 @@ public class TableInspector { ...@@ -58,36 +61,36 @@ public class TableInspector {
/** /**
* Tests to see if this TableInspector represents schema.table. * Tests to see if this TableInspector represents schema.table.
* <p> * <p>
* @param schema * @param schema the schema name
* @param table * @param table the table name
* @return * @return true if the table matches
*/ */
boolean matches(String schema, String table) { boolean matches(String schema, String table) {
if (isNullOrEmpty(schema)) if (isNullOrEmpty(schema)) {
// table name matching // table name matching
return this.table.equalsIgnoreCase(table); return this.table.equalsIgnoreCase(table);
else if (isNullOrEmpty(table)) } else if (isNullOrEmpty(table)) {
// schema name matching // schema name matching
return this.schema.equalsIgnoreCase(schema); return this.schema.equalsIgnoreCase(schema);
else } else {
// exact table matching // exact table matching
return this.schema.equalsIgnoreCase(schema) return this.schema.equalsIgnoreCase(schema)
&& this.table.equalsIgnoreCase(table); && this.table.equalsIgnoreCase(table);
} }
}
/** /**
* Reads the DatabaseMetaData for the details of this table including * Reads the DatabaseMetaData for the details of this table including
* primary keys and indexes. * primary keys and indexes.
* <p> *
* @param metadata * @param metaData the database meta data
* @throws SQLException
*/ */
void read(DatabaseMetaData metadata) throws SQLException { void read(DatabaseMetaData metaData) throws SQLException {
ResultSet rs = null; ResultSet rs = null;
// Primary Keys // Primary Keys
try { try {
rs = metadata.getPrimaryKeys(null, schema, table); rs = metaData.getPrimaryKeys(null, schema, table);
while (rs.next()) { while (rs.next()) {
String c = rs.getString("COLUMN_NAME"); String c = rs.getString("COLUMN_NAME");
primaryKeys.add(c); primaryKeys.add(c);
...@@ -95,23 +98,25 @@ public class TableInspector { ...@@ -95,23 +98,25 @@ public class TableInspector {
closeSilently(rs); closeSilently(rs);
// Indexes // Indexes
rs = metadata.getIndexInfo(null, schema, table, false, true); rs = metaData.getIndexInfo(null, schema, table, false, true);
indexes = Utils.newHashMap(); indexes = Utils.newHashMap();
while (rs.next()) { while (rs.next()) {
IndexInspector info = new IndexInspector(rs); IndexInspector info = new IndexInspector(rs);
if (info.type.equals(IndexType.UNIQUE) if (info.type.equals(IndexType.UNIQUE)
&& info.name.toLowerCase().startsWith("primary")) && info.name.toLowerCase().startsWith("primary")) {
// Skip PrimaryKey indexes // Skip PrimaryKey indexes
continue; continue;
if (indexes.containsKey(info.name)) }
if (indexes.containsKey(info.name)) {
indexes.get(info.name).addColumn(rs); indexes.get(info.name).addColumn(rs);
else } else {
indexes.put(info.name, info); indexes.put(info.name, info);
} }
}
closeSilently(rs); closeSilently(rs);
// Columns // Columns
rs = metadata.getColumns(null, schema, table, null); rs = metaData.getColumns(null, schema, table, null);
columns = Utils.newHashMap(); columns = Utils.newHashMap();
while (rs.next()) { while (rs.next()) {
ColumnInspector col = new ColumnInspector(); ColumnInspector col = new ColumnInspector();
...@@ -122,7 +127,7 @@ public class TableInspector { ...@@ -122,7 +127,7 @@ public class TableInspector {
// Allow Null // Allow Null
try { try {
col.allowNull = (rs.getInt("NULLABLE") == DatabaseMetaData.columnNullable); col.allowNull = rs.getInt("NULLABLE") == DatabaseMetaData.columnNullable;
} catch (SQLException x) { } catch (SQLException x) {
} }
...@@ -185,8 +190,9 @@ public class TableInspector { ...@@ -185,8 +190,9 @@ public class TableInspector {
StringBuilder fields = new StringBuilder(); StringBuilder fields = new StringBuilder();
List<ColumnInspector> sortedColumns = Utils.newArrayList(columns.values()); List<ColumnInspector> sortedColumns = Utils.newArrayList(columns.values());
Collections.sort(sortedColumns); Collections.sort(sortedColumns);
for (ColumnInspector col : sortedColumns) for (ColumnInspector col : sortedColumns) {
fields.append(generateColumn(imports, col, trimStrings)); fields.append(generateColumn(imports, col, trimStrings));
}
// Build Complete Class Definition // Build Complete Class Definition
StringBuilder model = new StringBuilder(); StringBuilder model = new StringBuilder();
...@@ -199,8 +205,9 @@ public class TableInspector { ...@@ -199,8 +205,9 @@ public class TableInspector {
// Imports // Imports
List<String> sortedImports = new ArrayList<String>(imports); List<String> sortedImports = new ArrayList<String>(imports);
Collections.sort(sortedImports); Collections.sort(sortedImports);
for (String imp : sortedImports) for (String imp : sortedImports) {
model.append("import ").append(imp).append(';').append(eol); model.append("import ").append(imp).append(';').append(eol);
}
model.append(eol); model.append(eol);
// @JQSchema // @JQSchema
...@@ -223,8 +230,9 @@ public class TableInspector { ...@@ -223,8 +230,9 @@ public class TableInspector {
if (primaryKeys.size() > 1) { if (primaryKeys.size() > 1) {
StringBuilder pk = new StringBuilder(); StringBuilder pk = new StringBuilder();
for (String key : primaryKeys) for (String key : primaryKeys) {
pk.append(key).append(' '); pk.append(key).append(' ');
}
pk.trimToSize(); pk.trimToSize();
ap.addParameter("primaryKey", pk.toString()); ap.addParameter("primaryKey", pk.toString());
} }
...@@ -270,15 +278,17 @@ public class TableInspector { ...@@ -270,15 +278,17 @@ public class TableInspector {
*/ */
void generateIndexAnnotations(AnnotationBuilder ap, String parameter, IndexType type) { void generateIndexAnnotations(AnnotationBuilder ap, String parameter, IndexType type) {
List<IndexInspector> list = getIndexes(type); List<IndexInspector> list = getIndexes(type);
if (list.size() == 0) if (list.size() == 0) {
// No matching indexes // No matching indexes
return; return;
}
if (list.size() == 1) { if (list.size() == 1) {
ap.addParameter(parameter, list.get(0).getColumnsString()); ap.addParameter(parameter, list.get(0).getColumnsString());
} else { } else {
List<String> parameters = Utils.newArrayList(); List<String> parameters = Utils.newArrayList();
for (IndexInspector index:list) for (IndexInspector index:list) {
parameters.add(index.getColumnsString()); parameters.add(index.getColumnsString());
}
ap.addParameter(parameter, parameters); ap.addParameter(parameter, parameters);
} }
...@@ -292,9 +302,11 @@ public class TableInspector { ...@@ -292,9 +302,11 @@ public class TableInspector {
*/ */
List<IndexInspector> getIndexes(IndexType type) { List<IndexInspector> getIndexes(IndexType type) {
List<IndexInspector> list = Utils.newArrayList(); List<IndexInspector> list = Utils.newArrayList();
for (IndexInspector index:indexes.values()) for (IndexInspector index:indexes.values()) {
if (index.type.equals(type)) if (index.type.equals(type)) {
list.add(index); list.add(index);
}
}
return list; return list;
} }
...@@ -358,8 +370,9 @@ public class TableInspector { ...@@ -358,8 +370,9 @@ public class TableInspector {
} }
// JQColumn.defaultValue // JQColumn.defaultValue
if (!isNullOrEmpty(col.defaultValue)) if (!isNullOrEmpty(col.defaultValue)) {
ap.addParameter("defaultValue=\"" + col.defaultValue + "\""); ap.addParameter("defaultValue=\"" + col.defaultValue + "\"");
}
// Add leading and trailing () // Add leading and trailing ()
if (ap.length() > 0) { if (ap.length() > 0) {
...@@ -421,13 +434,15 @@ public class TableInspector { ...@@ -421,13 +434,15 @@ public class TableInspector {
} }
// Index Validation // Index Validation
for (IndexInspector index:indexes.values()) for (IndexInspector index:indexes.values()) {
validate(remarks, def, index, throwError); validate(remarks, def, index, throwError);
}
// Field Column Validation // Field Column Validation
List<FieldDefinition> fieldDefs = def.getFields(); List<FieldDefinition> fieldDefs = def.getFields();
for (FieldDefinition fieldDef : fieldDefs) for (FieldDefinition fieldDef : fieldDefs) {
validate(remarks, fieldDef, throwError); validate(remarks, fieldDef, throwError);
}
return remarks; return remarks;
} }
...@@ -484,11 +499,11 @@ public class TableInspector { ...@@ -484,11 +499,11 @@ public class TableInspector {
// Supported Type Check // Supported Type Check
// JaQu maps to VARCHAR for unsupported types. // JaQu maps to VARCHAR for unsupported types.
if (fieldDef.dataType.equals("VARCHAR") if (fieldDef.dataType.equals("VARCHAR")
&& (fieldClazz != String.class)) && (fieldClazz != String.class)) {
remarks.add(ERROR(table, fieldDef, remarks.add(ERROR(table, fieldDef,
"JaQu does not currently implement support for " "JaQu does not currently implement support for "
+ fieldClazz.getName()).throwError(throwError)); + fieldClazz.getName()).throwError(throwError));
}
// Number Types // Number Types
if (!fieldClazz.equals(jdbcClazz)) { if (!fieldClazz.equals(jdbcClazz)) {
if (Number.class.isAssignableFrom(fieldClazz)) { if (Number.class.isAssignableFrom(fieldClazz)) {
...@@ -507,27 +522,28 @@ public class TableInspector { ...@@ -507,27 +522,28 @@ public class TableInspector {
// String Types // String Types
if (fieldClazz == String.class) { if (fieldClazz == String.class) {
if ((fieldDef.maxLength != col.size) if ((fieldDef.maxLength != col.size)
&& (col.size < Integer.MAX_VALUE)) && (col.size < Integer.MAX_VALUE)) {
remarks.add(WARN(table, col, remarks.add(WARN(table, col,
format("{0}.maxLength={1}, ColumnMaxLength={2}", format("{0}.maxLength={1}, ColumnMaxLength={2}",
JQColumn.class.getSimpleName(), JQColumn.class.getSimpleName(),
fieldDef.maxLength, col.size))); fieldDef.maxLength, col.size)));
}
if (fieldDef.maxLength > 0 && !fieldDef.trimString) if (fieldDef.maxLength > 0 && !fieldDef.trimString) {
remarks.add(CONSIDER(table, col, remarks.add(CONSIDER(table, col,
format("{0}.truncateToMaxLength=true" format("{0}.truncateToMaxLength=true"
+ " will prevent RuntimeExceptions on" + " will prevent RuntimeExceptions on"
+ " INSERTs or UPDATEs, but will clip data!", + " INSERTs or UPDATEs, but will clip data!",
JQColumn.class.getSimpleName()))); JQColumn.class.getSimpleName())));
} }
}
// Numeric AutoIncrement // Numeric AutoIncrement
if (fieldDef.isAutoIncrement != col.isAutoIncrement) if (fieldDef.isAutoIncrement != col.isAutoIncrement) {
remarks.add(WARN(table, col, format("{0}.isAutoIncrement={1}" remarks.add(WARN(table, col, format("{0}.isAutoIncrement={1}"
+ " while Column autoIncrement={2}", + " while Column autoIncrement={2}",
JQColumn.class.getSimpleName(), fieldDef.isAutoIncrement, JQColumn.class.getSimpleName(), fieldDef.isAutoIncrement,
col.isAutoIncrement))); col.isAutoIncrement)));
}
// Last Check // Last Check
// Default Value... // Default Value...
if (!col.isAutoIncrement && !col.isPrimaryKey) { if (!col.isAutoIncrement && !col.isPrimaryKey) {
...@@ -593,15 +609,15 @@ public class TableInspector { ...@@ -593,15 +609,15 @@ public class TableInspector {
boolean hash = rs.getInt("TYPE") == DatabaseMetaData.tableIndexHashed; boolean hash = rs.getInt("TYPE") == DatabaseMetaData.tableIndexHashed;
boolean unique = !rs.getBoolean("NON_UNIQUE"); boolean unique = !rs.getBoolean("NON_UNIQUE");
if (!hash && !unique) if (!hash && !unique) {
type = IndexType.STANDARD; type = IndexType.STANDARD;
else if (hash && unique) } else if (hash && unique) {
type = IndexType.UNIQUE_HASH; type = IndexType.UNIQUE_HASH;
else if (unique) } else if (unique) {
type = IndexType.UNIQUE; type = IndexType.UNIQUE;
else if (hash) } else if (hash) {
type = IndexType.HASH; type = IndexType.HASH;
}
columns.add(rs.getString("COLUMN_NAME")); columns.add(rs.getString("COLUMN_NAME"));
} }
...@@ -624,31 +640,31 @@ public class TableInspector { ...@@ -624,31 +640,31 @@ public class TableInspector {
* *
*/ */
public static class ColumnInspector implements Comparable<ColumnInspector> { public static class ColumnInspector implements Comparable<ColumnInspector> {
String name = null; String name;
String type = null; String type;
int size = 0; int size;
boolean allowNull = false; boolean allowNull;
Class<?> clazz = null; Class<?> clazz;
boolean isPrimaryKey = false; boolean isPrimaryKey;
boolean isAutoIncrement = false; boolean isAutoIncrement;
String defaultValue = null; String defaultValue;
@Override
public int compareTo(ColumnInspector o) { public int compareTo(ColumnInspector o) {
if (isPrimaryKey && o.isPrimaryKey) if (isPrimaryKey && o.isPrimaryKey) {
// both primary sort by name // both primary sort by name
return name.compareTo(o.name); return name.compareTo(o.name);
else if (isPrimaryKey && !o.isPrimaryKey) } else if (isPrimaryKey && !o.isPrimaryKey) {
// primary first // primary first
return -1; return -1;
else if (!isPrimaryKey && o.isPrimaryKey) } else if (!isPrimaryKey && o.isPrimaryKey) {
// primary first // primary first
return 1; return 1;
else } else {
// Neither primary, sort by name // Neither primary, sort by name
return name.compareTo(o.name); return name.compareTo(o.name);
} }
} }
}
/** /**
* Convenience class based on StatementBuilder for creating the * Convenience class based on StatementBuilder for creating the
...@@ -675,21 +691,27 @@ public class TableInspector { ...@@ -675,21 +691,27 @@ public class TableInspector {
StatementBuilder flat = new StatementBuilder(); StatementBuilder flat = new StatementBuilder();
for (Object o:list) { for (Object o:list) {
flat.appendExceptFirst(", "); flat.appendExceptFirst(", ");
if (o instanceof String) if (o instanceof String) {
flat.append('\"'); flat.append('\"');
}
int todoEscape;
flat.append(o.toString().trim()); flat.append(o.toString().trim());
if (o instanceof String) if (o instanceof String) {
flat.append('\"'); flat.append('\"');
} }
}
append(flat); append(flat);
append(" }"); append(" }");
} else { } else {
if (value instanceof String) if (value instanceof String) {
append('\"'); append('\"');
}
int todoEscape;
append(value.toString().trim()); append(value.toString().trim());
if (value instanceof String) if (value instanceof String) {
append('\"'); append('\"');
} }
} }
} }
}
} }
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论