提交 113996ea authored 作者: Thomas Mueller's avatar Thomas Mueller

Cleanup:

- Javadocs
- Work in progress
上级 daa2b0bf
...@@ -19,7 +19,6 @@ import org.h2.jaqu.bytecode.ClassReader; ...@@ -19,7 +19,6 @@ import org.h2.jaqu.bytecode.ClassReader;
import org.h2.jaqu.util.StatementLogger; import org.h2.jaqu.util.StatementLogger;
import org.h2.jaqu.util.JdbcUtils; import org.h2.jaqu.util.JdbcUtils;
import org.h2.jaqu.util.Utils; import org.h2.jaqu.util.Utils;
//import org.h2.util.JdbcUtils;
//## Java 1.5 end ## //## Java 1.5 end ##
/** /**
...@@ -38,8 +37,8 @@ public class Query<T> { ...@@ -38,8 +37,8 @@ public class Query<T> {
private final IdentityHashMap<Object, SelectColumn<T>> aliasMap = Utils.newIdentityHashMap(); private final IdentityHashMap<Object, SelectColumn<T>> aliasMap = Utils.newIdentityHashMap();
private ArrayList<OrderExpression<T>> orderByList = Utils.newArrayList(); private ArrayList<OrderExpression<T>> orderByList = Utils.newArrayList();
private Object[] groupByExpressions; private Object[] groupByExpressions;
private long limit = 0; private long limit;
private long offset = 0; private long offset;
Query(Db db) { Query(Db db) {
this.db = db; this.db = db;
...@@ -65,6 +64,7 @@ public class Query<T> { ...@@ -65,6 +64,7 @@ public class Query<T> {
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} finally { } finally {
int whyTrue;
JdbcUtils.closeSilently(rs, true); JdbcUtils.closeSilently(rs, true);
} }
} }
...@@ -122,10 +122,12 @@ public class Query<T> { ...@@ -122,10 +122,12 @@ public class Query<T> {
} }
public <A> SetColumn<T, A> set(A field) { public <A> SetColumn<T, A> set(A field) {
int renameSetColumnClassToUpdateSetColumn;
return new SetColumn<T, A>(this, field); return new SetColumn<T, A>(this, field);
} }
public <A> IncrementColumn<T, A> increment(A field) { public <A> IncrementColumn<T, A> increment(A field) {
int renameIncrementColumnClassToUpdateIncrementColumn;
return new IncrementColumn<T, A>(this, field); return new IncrementColumn<T, A>(this, field);
} }
...@@ -137,7 +139,7 @@ public class Query<T> { ...@@ -137,7 +139,7 @@ public class Query<T> {
from.appendSQL(stat); from.appendSQL(stat);
stat.appendSQL(" SET "); stat.appendSQL(" SET ");
int i = 0; int i = 0;
for (Declaration declaration:declarations) { for (Declaration declaration : declarations) {
if (i++ > 0) { if (i++ > 0) {
stat.appendSQL(", "); stat.appendSQL(", ");
} }
...@@ -196,6 +198,7 @@ public class Query<T> { ...@@ -196,6 +198,7 @@ public class Query<T> {
try { try {
X value; X value;
Object o = rs.getObject(1); Object o = rs.getObject(1);
int convertHereIsProbablyWrong;
if (Clob.class.isAssignableFrom(o.getClass())) { if (Clob.class.isAssignableFrom(o.getClass())) {
value = (X) Utils.convert(o, String.class); value = (X) Utils.convert(o, String.class);
} else } else
...@@ -325,6 +328,7 @@ public class Query<T> { ...@@ -325,6 +328,7 @@ public class Query<T> {
} }
void addDeclarationToken(Declaration declaration) { void addDeclarationToken(Declaration declaration) {
int todoWhatIsDeclaration;
declarations.add(declaration); declarations.add(declaration);
} }
......
...@@ -82,8 +82,9 @@ public class SQLStatement { ...@@ -82,8 +82,9 @@ public class SQLStatement {
ps.executeUpdate(); ps.executeUpdate();
long identity = -1; long identity = -1;
ResultSet rs = ps.getGeneratedKeys(); ResultSet rs = ps.getGeneratedKeys();
if (rs != null && rs.next()) if (rs != null && rs.next()) {
identity = rs.getLong(1); identity = rs.getLong(1);
}
JdbcUtils.closeSilently(rs); JdbcUtils.closeSilently(rs);
return identity; return identity;
} catch (SQLException e) { } catch (SQLException e) {
...@@ -101,8 +102,8 @@ public class SQLStatement { ...@@ -101,8 +102,8 @@ public class SQLStatement {
} }
} }
private PreparedStatement prepare(boolean returnIdentity) { private PreparedStatement prepare(boolean returnGeneratedKeys) {
PreparedStatement prep = db.prepare(getSQL(), returnIdentity); PreparedStatement prep = db.prepare(getSQL(), returnGeneratedKeys);
for (int i = 0; i < params.size(); i++) { for (int i = 0; i < params.size(); i++) {
Object o = params.get(i); Object o = params.get(i);
setValue(prep, i + 1, o); setValue(prep, i + 1, o);
......
/* /*
* Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License, Version * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
* 1.0, and under the Eclipse Public License, Version 1.0 * Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html). Initial Developer: H2 Group * (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/ */
package org.h2.jaqu; package org.h2.jaqu;
...@@ -10,6 +11,9 @@ import java.lang.annotation.Retention; ...@@ -10,6 +11,9 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
/**
* A class that implements this interface can be used as a database table.
*/
/** /**
* A class that implements the JaQu model mapping options. * A class that implements the JaQu model mapping options.
* <p> * <p>
...@@ -116,8 +120,9 @@ import java.lang.annotation.Target; ...@@ -116,8 +120,9 @@ import java.lang.annotation.Target;
* <pre> * <pre>
* Db db = Db.open(&quot;jdbc:h2:mem:&quot;, &quot;sa&quot;, &quot;sa&quot;); * Db db = Db.open(&quot;jdbc:h2:mem:&quot;, &quot;sa&quot;, &quot;sa&quot;);
* DbInspector inspector = new DbInspector(db); * DbInspector inspector = new DbInspector(db);
* List&lt;String&gt; models = inspector.generateModel(schema, table, * List&lt;String&gt; models =
* packageName, annotateSchema, trimStrings); * inspector.generateModel(schema, table, packageName,
* annotateSchema, trimStrings)
* </pre> * </pre>
* *
* OR you may use the <i>GenerateModels</i> tool to generate and save your * OR you may use the <i>GenerateModels</i> tool to generate and save your
...@@ -134,33 +139,34 @@ import java.lang.annotation.Target; ...@@ -134,33 +139,34 @@ import java.lang.annotation.Target;
* <b>Model Validation</b> * <b>Model Validation</b>
* <p> * <p>
* You may validate your model class with <i>DbInspector</i> object.<br> * You may validate your model class with <i>DbInspector</i> object.<br>
* The DbInspector will report ERRORS, WARNINGS, and SUGGESTIONS to help you. * The DbInspector will report ERRORS, WARNINGS, and
* SUGGESTIONS to help you.
* *
* <pre> * <pre>
* Db db = Db.open(&quot;jdbc:h2:mem:&quot;, &quot;sa&quot;, &quot;sa&quot;); * Db db = Db.open(&quot;jdbc:h2:mem:&quot;,
* &quot;sa&quot;, &quot;sa&quot;);
* DbInspector inspector = new DbInspector(db); * DbInspector inspector = new DbInspector(db);
* MyModel model = new MyModel(); * List&lt;Validation&gt; remarks =
* List&lt;Validation&gt; remarks = inspector.validateModel(model, throwOnError); * inspector.validateModel(new MyModel(), throwOnError);
* for (Validation remark : remarks) * for (Validation remark : remarks) {
* System.out.println(remark); * System.out.println(remark);
* }
* </pre> * </pre>
*/ */
public interface Table { public interface Table {
static final int reviewWholeClassAndJavadocs = 0;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
public @interface JQDatabase { public @interface JQDatabase {
/** /**
* If <b>version</b> is set to a <i>non-zero</i> value, JaQu will * If version is set to a non-zero value, JaQu will
* maintain a "_jq_versions" table within your database. The * maintain a "_jq_versions" table within your database. The
* <i>version</i> number will be used to call to a registered * version number will be used to call to a registered
* <i>DbUpgrader</i> implementation to perform relevant ALTERs or * DbUpgrader implementation to perform relevant ALTER statements.
* whatever. * Default: 0.
* <p> * You must specify a DbUpgrader on your Db object to
* <b>Default: <i>0</i></b>
* <p>
* <b>NOTE:</b><br>
* You must specify a <i>DbUpgrader</i> on your <i>Db</i> object to
* use this parameter. * use this parameter.
*/ */
int version() default 0; int version() default 0;
...@@ -170,17 +176,14 @@ public interface Table { ...@@ -170,17 +176,14 @@ public interface Table {
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
public @interface JQSchema { public @interface JQSchema {
/** /**
* <b>schema</b> may be optionally specified. If it is not specified the * The schema may be optionally specified. If it is not specified the
* schema will be ignored. * schema will be ignored. Default: Unspecified.
* <p>
* <b>Default: <i>Unspecified</i></b>
*/ */
String name() default ""; String name() default "";
} }
/** /**
* Enumeration defining the 4 index types. * Enumeration defining the 4 index types.
*
*/ */
public static enum IndexType { public static enum IndexType {
STANDARD, UNIQUE, HASH, UNIQUE_HASH; STANDARD, UNIQUE, HASH, UNIQUE_HASH;
...@@ -190,17 +193,16 @@ public interface Table { ...@@ -190,17 +193,16 @@ public interface Table {
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
public @interface JQIndex { public @interface JQIndex {
/** /**
* <b>standard</b> indexes may be optionally specified. If not specified, * Standard indexes may be optionally specified. If not specified,
* these values will be ignored. * these values will be ignored.
* <ul> * <ul>
* <li>standard = "id, name" * <li>standard = "id, name"
* <li>standard = "id name" * <li>standard = "id name"
* <li>standard = { "id name", "date" } * <li>standard = { "id name", "date" }
* </ul> * </ul>
* Standard indexes may still be added in the <i>define()</i> method if * Standard indexes may still be added in the define() method if
* the model class is not annotated with JQTable. * the model class is not annotated with JQTable.
* <p> * Default: Unspecified.
* <b>Default: <i>Unspecified</i></b>
*/ */
String[] standard() default {}; String[] standard() default {};
...@@ -337,8 +339,8 @@ public interface Table { ...@@ -337,8 +339,8 @@ public interface Table {
* If <b>version</b> is set to a <i>non-zero</i> value, JaQu will * If <b>version</b> is set to a <i>non-zero</i> value, JaQu will
* maintain a "_jq_versions" table within your database. The * maintain a "_jq_versions" table within your database. The
* <i>version</i> number will be used to call to a registered * <i>version</i> number will be used to call to a registered
* <i>DbUpgrader</i> implementation to perform relevant ALTERs or * <i>DbUpgrader</i> implementation to perform relevant ALTER
* whatever. * statements.
* <p> * <p>
* <b>Default: <i>0</i></b> * <b>Default: <i>0</i></b>
* <p> * <p>
......
...@@ -39,6 +39,8 @@ import org.h2.jaqu.util.Utils; ...@@ -39,6 +39,8 @@ import org.h2.jaqu.util.Utils;
*/ */
public class TableInspector { public class TableInspector {
private final static int todoReviewClass = 0;
private String schema; private String schema;
private String table; private String table;
private boolean forceUpperCase; private boolean forceUpperCase;
...@@ -48,8 +50,6 @@ public class TableInspector { ...@@ -48,8 +50,6 @@ public class TableInspector {
private Map<String, ColumnInspector> columns; private Map<String, ColumnInspector> columns;
private final String eol = "\n"; 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) {
this.schema = schema; this.schema = schema;
...@@ -88,7 +88,7 @@ public class TableInspector { ...@@ -88,7 +88,7 @@ public class TableInspector {
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()) {
...@@ -97,14 +97,14 @@ public class TableInspector { ...@@ -97,14 +97,14 @@ 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 primary key indexes
continue; continue;
} }
if (indexes.containsKey(info.name)) { if (indexes.containsKey(info.name)) {
...@@ -115,7 +115,7 @@ public class TableInspector { ...@@ -115,7 +115,7 @@ public class TableInspector {
} }
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()) {
...@@ -124,35 +124,15 @@ public class TableInspector { ...@@ -124,35 +124,15 @@ public class TableInspector {
col.type = rs.getString("TYPE_NAME"); col.type = rs.getString("TYPE_NAME");
col.clazz = ModelUtils.getClassType(col.type, dateClazz); col.clazz = ModelUtils.getClassType(col.type, dateClazz);
col.size = rs.getInt("COLUMN_SIZE"); col.size = rs.getInt("COLUMN_SIZE");
// Allow Null
try {
col.allowNull = rs.getInt("NULLABLE") == DatabaseMetaData.columnNullable; col.allowNull = rs.getInt("NULLABLE") == DatabaseMetaData.columnNullable;
} catch (SQLException x) {
}
// AutoIncrement
try {
col.isAutoIncrement = rs.getBoolean("IS_AUTOINCREMENT"); col.isAutoIncrement = rs.getBoolean("IS_AUTOINCREMENT");
} catch (SQLException x) {
}
// Primary Key
if (primaryKeys.size() == 1) { if (primaryKeys.size() == 1) {
if (col.name.equalsIgnoreCase(primaryKeys.get(0))) if (col.name.equalsIgnoreCase(primaryKeys.get(0))) {
col.isPrimaryKey = true; col.isPrimaryKey = true;
} }
}
// Default Value
if (!col.isAutoIncrement) { if (!col.isAutoIncrement) {
try {
col.defaultValue = rs.getString("COLUMN_DEFAULT");
} catch (SQLException t) {
try {
col.defaultValue = rs.getString("COLUMN_DEF"); col.defaultValue = rs.getString("COLUMN_DEF");
} catch (SQLException x) {
}
}
} }
columns.put(col.name, col); columns.put(col.name, col);
} }
...@@ -179,14 +159,14 @@ public class TableInspector { ...@@ -179,14 +159,14 @@ public class TableInspector {
String generateModel(String packageName, boolean annotateSchema, String generateModel(String packageName, boolean annotateSchema,
boolean trimStrings) { boolean trimStrings) {
// Set of imports // import statements
Set<String> imports = Utils.newHashSet(); Set<String> imports = Utils.newHashSet();
imports.add(JQSchema.class.getCanonicalName()); imports.add(JQSchema.class.getCanonicalName());
imports.add(JQTable.class.getCanonicalName()); imports.add(JQTable.class.getCanonicalName());
imports.add(JQIndex.class.getCanonicalName()); imports.add(JQIndex.class.getCanonicalName());
imports.add(JQColumn.class.getCanonicalName()); imports.add(JQColumn.class.getCanonicalName());
// Table Fields // fields
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);
...@@ -194,15 +174,15 @@ public class TableInspector { ...@@ -194,15 +174,15 @@ public class TableInspector {
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();
if (!isNullOrEmpty(packageName)) { if (!isNullOrEmpty(packageName)) {
// Package // package
model.append("package " + packageName + ";"); model.append("package " + packageName + ";");
model.append(eol).append(eol); model.append(eol).append(eol);
} }
// 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) {
...@@ -224,7 +204,7 @@ public class TableInspector { ...@@ -224,7 +204,7 @@ public class TableInspector {
model.append('@').append(JQTable.class.getSimpleName()); model.append('@').append(JQTable.class.getSimpleName());
model.append('('); model.append('(');
// JQTable Annotation Parameters // JQTable annotation parameters
AnnotationBuilder ap = new AnnotationBuilder(); AnnotationBuilder ap = new AnnotationBuilder();
ap.addParameter("name", table); ap.addParameter("name", table);
...@@ -237,7 +217,7 @@ public class TableInspector { ...@@ -237,7 +217,7 @@ public class TableInspector {
ap.addParameter("primaryKey", pk.toString()); ap.addParameter("primaryKey", pk.toString());
} }
// Finish @JQTable annotation // finish @JQTable annotation
model.append(ap); model.append(ap);
model.append(')').append(eol); model.append(')').append(eol);
...@@ -254,19 +234,19 @@ public class TableInspector { ...@@ -254,19 +234,19 @@ public class TableInspector {
model.append(')').append(eol); model.append(')').append(eol);
} }
// Class Declaration // class declaration
String clazzName = ModelUtils.createClassName(table); String clazzName = ModelUtils.createClassName(table);
model.append(format("public class {0} '{'", clazzName)).append(eol); model.append(format("public class {0} '{'", clazzName)).append(eol);
model.append(eol); model.append(eol);
// Field Declarations // field declarations
model.append(fields); model.append(fields);
// Default Constructor // default constructor
model.append("\tpublic ").append(clazzName).append("() {").append(eol); model.append("\t" + "public ").append(clazzName).append("() {").append(eol);
model.append("\t}").append(eol); model.append("\t}").append(eol);
// End of Class Body // end of class body
model.append('}'); model.append('}');
model.trimToSize(); model.trimToSize();
return model.toString(); return model.toString();
...@@ -279,7 +259,7 @@ public class TableInspector { ...@@ -279,7 +259,7 @@ 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) {
...@@ -323,27 +303,27 @@ public class TableInspector { ...@@ -323,27 +303,27 @@ public class TableInspector {
boolean trimStrings) { boolean trimStrings) {
StatementBuilder sb = new StatementBuilder(); StatementBuilder sb = new StatementBuilder();
Class<?> clazz = col.clazz; Class<?> clazz = col.clazz;
String cname = ModelUtils.createFieldName(col.name.toLowerCase()); String column = ModelUtils.createFieldName(col.name.toLowerCase());
sb.append('\t'); sb.append('\t');
if (clazz == null) { if (clazz == null) {
// Unsupported Type // unsupported type
clazz = Object.class; clazz = Object.class;
sb.append("// Unsupported type " + col.type); sb.append("// unsupported type " + col.type);
} else { } else {
// @JQColumn // @JQColumn
imports.add(clazz.getCanonicalName()); imports.add(clazz.getCanonicalName());
sb.append('@').append(JQColumn.class.getSimpleName()); sb.append('@').append(JQColumn.class.getSimpleName());
// JQColumn Annotation Parameters // JQColumn annotation parameters
AnnotationBuilder ap = new AnnotationBuilder(); AnnotationBuilder ap = new AnnotationBuilder();
// JQColumn.name // JQColumn.name
if (!col.name.equalsIgnoreCase(cname)) { if (!col.name.equalsIgnoreCase(column)) {
ap.addParameter("name", col.name); ap.addParameter("name", col.name);
} }
// JQColumn.primaryKey // JQColumn.primaryKey
// Composite Primary Keys are annotated on the Table // composite primary keys are annotated on the table
if (col.isPrimaryKey && primaryKeys.size() == 1) { if (col.isPrimaryKey && primaryKeys.size() == 1) {
ap.addParameter("primaryKey=true"); ap.addParameter("primaryKey=true");
} }
...@@ -374,7 +354,7 @@ public class TableInspector { ...@@ -374,7 +354,7 @@ public class TableInspector {
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) {
ap.insert(0, '('); ap.insert(0, '(');
ap.append(')'); ap.append(')');
...@@ -383,11 +363,11 @@ public class TableInspector { ...@@ -383,11 +363,11 @@ public class TableInspector {
} }
sb.append(eol); sb.append(eol);
// Variable Declaration // variable declaration
sb.append("\tpublic "); sb.append("\tpublic ");
sb.append(clazz.getSimpleName()); sb.append(clazz.getSimpleName());
sb.append(' '); sb.append(' ');
sb.append(cname); sb.append(column);
sb.append(';'); sb.append(';');
sb.append(eol).append(eol); sb.append(eol).append(eol);
return sb; return sb;
...@@ -400,9 +380,10 @@ public class TableInspector { ...@@ -400,9 +380,10 @@ public class TableInspector {
* Results are returned as a List&lt;Validation&gt; which includes * Results are returned as a List&lt;Validation&gt; which includes
* recommendations, warnings, and errors about the model. * recommendations, warnings, and errors about the model.
* <p> * <p>
* The caller may choose to have validate throw an exception on any validation * The caller may choose to have validate throw an exception on any
* ERROR. * validation ERROR.
* <p> * <p>
*
* @param <T> * @param <T>
* @param def * @param def
* @param throwError * @param throwError
...@@ -412,7 +393,7 @@ public class TableInspector { ...@@ -412,7 +393,7 @@ public class TableInspector {
boolean throwError) { boolean throwError) {
List<Validation> remarks = Utils.newArrayList(); List<Validation> remarks = Utils.newArrayList();
// Model Class Definition Validation // model class definition validation
if (!Modifier.isPublic(def.getModelClass().getModifiers())) { if (!Modifier.isPublic(def.getModelClass().getModifiers())) {
remarks.add(ERROR(table, "SCHEMA", remarks.add(ERROR(table, "SCHEMA",
format("Class {0} MUST BE PUBLIC!", format("Class {0} MUST BE PUBLIC!",
...@@ -433,14 +414,13 @@ public class TableInspector { ...@@ -433,14 +414,13 @@ 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(); for (FieldDefinition fieldDef : def.getFields()) {
for (FieldDefinition fieldDef : fieldDefs) {
validate(remarks, fieldDef, throwError); validate(remarks, fieldDef, throwError);
} }
return remarks; return remarks;
...@@ -467,7 +447,7 @@ public class TableInspector { ...@@ -467,7 +447,7 @@ public class TableInspector {
} else if (defIndexes.size() < dbIndexes.size()) { } else if (defIndexes.size() < dbIndexes.size()) {
remarks.add(WARN(table, IndexType.STANDARD.name(), "Model class is missing indexes!")); remarks.add(WARN(table, IndexType.STANDARD.name(), "Model class is missing indexes!"));
} }
// TODO Complete index validation. // TODO complete index validation.
// Need to actually compare index types and columns within each index. // Need to actually compare index types and columns within each index.
// At this point my head was starting to hurt. // At this point my head was starting to hurt.
} }
...@@ -483,20 +463,20 @@ public class TableInspector { ...@@ -483,20 +463,20 @@ public class TableInspector {
*/ */
void validate(List<Validation> remarks, FieldDefinition fieldDef, void validate(List<Validation> remarks, FieldDefinition fieldDef,
boolean throwError) { boolean throwError) {
// Unknown Field // unknown field
String fname = forceUpperCase ? String field = forceUpperCase ?
fieldDef.columnName.toUpperCase() : fieldDef.columnName; fieldDef.columnName.toUpperCase() : fieldDef.columnName;
if (!columns.containsKey(fname)) { if (!columns.containsKey(field)) {
// Unknown column mapping! // unknown column mapping
remarks.add(ERROR(table, fieldDef, remarks.add(ERROR(table, fieldDef,
"Does not exist in database!").throwError(throwError)); "Does not exist in database!").throwError(throwError));
return; return;
} }
ColumnInspector col = columns.get(fname); ColumnInspector col = columns.get(field);
Class<?> fieldClazz = fieldDef.field.getType(); Class<?> fieldClazz = fieldDef.field.getType();
Class<?> jdbcClazz = ModelUtils.getClassType(col.type, dateClazz); Class<?> jdbcClazz = ModelUtils.getClassType(col.type, dateClazz);
// 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)) {
...@@ -504,7 +484,7 @@ public class TableInspector { ...@@ -504,7 +484,7 @@ public class TableInspector {
"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)) {
remarks.add(WARN(table, col, remarks.add(WARN(table, col,
...@@ -519,7 +499,7 @@ public class TableInspector { ...@@ -519,7 +499,7 @@ 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)) {
...@@ -532,31 +512,31 @@ public class TableInspector { ...@@ -532,31 +512,31 @@ public class TableInspector {
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!", + " INSERT or UPDATE, 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) {
// Check Model.defaultValue Format // check Model.defaultValue format
if (!ModelUtils.isProperlyFormattedDefaultValue(fieldDef.defaultValue)) { if (!ModelUtils.isProperlyFormattedDefaultValue(fieldDef.defaultValue)) {
remarks.add(ERROR(table, col, format("{0}.defaultValue=\"{1}\"" remarks.add(ERROR(table, col, format("{0}.defaultValue=\"{1}\""
+ " is improperly formatted!", + " is improperly formatted!",
JQColumn.class.getSimpleName(), JQColumn.class.getSimpleName(),
fieldDef.defaultValue)).throwError(throwError)); fieldDef.defaultValue)).throwError(throwError));
// Next field // next field
return; return;
} }
// Compare Model.defaultValue to Column.defaultValue // compare Model.defaultValue to Column.defaultValue
if (isNullOrEmpty(fieldDef.defaultValue) if (isNullOrEmpty(fieldDef.defaultValue)
&& !isNullOrEmpty(col.defaultValue)) { && !isNullOrEmpty(col.defaultValue)) {
// Model.defaultValue is NULL, Column.defaultValue is NOT NULL // Model.defaultValue is NULL, Column.defaultValue is NOT NULL
...@@ -580,7 +560,7 @@ public class TableInspector { ...@@ -580,7 +560,7 @@ public class TableInspector {
} }
} }
// Sanity Check Model.defaultValue Literal Value // sanity check Model.defaultValue literal value
if (!ModelUtils.isValidDefaultValue(fieldDef.field.getType(), if (!ModelUtils.isValidDefaultValue(fieldDef.field.getType(),
fieldDef.defaultValue)) { fieldDef.defaultValue)) {
remarks.add(ERROR(table, col, remarks.add(ERROR(table, col,
...@@ -593,7 +573,6 @@ public class TableInspector { ...@@ -593,7 +573,6 @@ public class TableInspector {
/** /**
* Represents an index as it exists in the database. * Represents an index as it exists in the database.
*
*/ */
public static class IndexInspector { public static class IndexInspector {
String name; String name;
...@@ -605,7 +584,7 @@ public class TableInspector { ...@@ -605,7 +584,7 @@ public class TableInspector {
public IndexInspector(ResultSet rs) throws SQLException { public IndexInspector(ResultSet rs) throws SQLException {
name = rs.getString("INDEX_NAME"); name = rs.getString("INDEX_NAME");
// Determine Index Type // determine index type
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");
...@@ -660,7 +639,7 @@ public class TableInspector { ...@@ -660,7 +639,7 @@ public class TableInspector {
// 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);
} }
} }
......
...@@ -19,6 +19,8 @@ import org.h2.jaqu.util.StringUtils; ...@@ -19,6 +19,8 @@ import org.h2.jaqu.util.StringUtils;
*/ */
public class Validation { public class Validation {
private int todoReviewWholeClass;
public static Validation CONSIDER(String table, String type, String message) { public static Validation CONSIDER(String table, String type, String message) {
return new Validation(Level.CONSIDER, table, type, message); return new Validation(Level.CONSIDER, table, type, message);
} }
......
...@@ -13,6 +13,8 @@ package org.h2.jaqu.util; ...@@ -13,6 +13,8 @@ package org.h2.jaqu.util;
*/ */
public class ClassUtils { public class ClassUtils {
int todoDelete;
private ClassUtils() { private ClassUtils() {
// utility class // utility class
} }
...@@ -31,5 +33,7 @@ public class ClassUtils { ...@@ -31,5 +33,7 @@ public class ClassUtils {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
//## Java 1.5 end ## //## Java 1.5 end ##
} }
...@@ -28,6 +28,8 @@ import org.h2.message.DbException; ...@@ -28,6 +28,8 @@ import org.h2.message.DbException;
*/ */
public class GenerateModels { public class GenerateModels {
private static final int todoReview = 0;
/** /**
* The output stream where this tool writes to. * The output stream where this tool writes to.
*/ */
...@@ -112,10 +114,11 @@ public class GenerateModels { ...@@ -112,10 +114,11 @@ public class GenerateModels {
List<String> models = inspector.generateModel(schema, table, List<String> models = inspector.generateModel(schema, table,
packageName, annotateSchema, trimStrings); packageName, annotateSchema, trimStrings);
File parentFile; File parentFile;
if (StringUtils.isNullOrEmpty(folder)) if (StringUtils.isNullOrEmpty(folder)) {
parentFile = new File(System.getProperty("user.dir")); parentFile = new File(System.getProperty("user.dir"));
else } else {
parentFile = new File(folder); parentFile = new File(folder);
}
parentFile.mkdirs(); parentFile.mkdirs();
Pattern p = Pattern.compile("class ([a-zA-Z0-9]+)"); Pattern p = Pattern.compile("class ([a-zA-Z0-9]+)");
for (String model : models) { for (String model : models) {
...@@ -162,4 +165,5 @@ public class GenerateModels { ...@@ -162,4 +165,5 @@ public class GenerateModels {
out.println(" -annotateSchema <boolean>"); out.println(" -annotateSchema <boolean>");
out.println(" -trimStrings <boolean>"); out.println(" -trimStrings <boolean>");
} }
} }
...@@ -21,6 +21,8 @@ import javax.sql.XAConnection; ...@@ -21,6 +21,8 @@ import javax.sql.XAConnection;
*/ */
public class JdbcUtils { public class JdbcUtils {
private static final int todoDeleteClass = 0;
private static final String[] DRIVERS = { private static final String[] DRIVERS = {
"h2:", "org.h2.Driver", "h2:", "org.h2.Driver",
"Cache:", "com.intersys.jdbc.CacheDriver", "Cache:", "com.intersys.jdbc.CacheDriver",
......
...@@ -18,6 +18,8 @@ import java.sql.SQLException; ...@@ -18,6 +18,8 @@ import java.sql.SQLException;
*/ */
public class Message { public class Message {
private int todoDelete;
private Message() { private Message() {
// utility class // utility class
} }
......
...@@ -30,6 +30,8 @@ package org.h2.jaqu.util; ...@@ -30,6 +30,8 @@ package org.h2.jaqu.util;
*/ */
public class StatementBuilder { public class StatementBuilder {
private int todoDelete;
private final StringBuilder builder = new StringBuilder(); private final StringBuilder builder = new StringBuilder();
private int index; private int index;
......
...@@ -20,72 +20,67 @@ import java.util.concurrent.atomic.AtomicLong; ...@@ -20,72 +20,67 @@ import java.util.concurrent.atomic.AtomicLong;
*/ */
public class StatementLogger { public class StatementLogger {
public static boolean logStatements = false; public static boolean logStatements;
private static PrintWriter out = new PrintWriter(System.out);
public static PrintWriter out = new PrintWriter(System.out); private static final AtomicLong SELECT_COUNT = new AtomicLong();
private static final AtomicLong CREATE_COUNT = new AtomicLong();
public final static AtomicLong selectCount = new AtomicLong(0); private static final AtomicLong INSERT_COUNT = new AtomicLong();
private static final AtomicLong UPDATE_COUNT = new AtomicLong();
public final static AtomicLong createCount = new AtomicLong(0); private static final AtomicLong MERGE_COUNT = new AtomicLong();
private static final AtomicLong DELETE_COUNT = new AtomicLong();
public final static AtomicLong insertCount = new AtomicLong(0);
public final static AtomicLong updateCount = new AtomicLong(0);
public final static AtomicLong mergeCount = new AtomicLong(0);
public final static AtomicLong deleteCount = new AtomicLong(0);
public static void create(String statement) { public static void create(String statement) {
createCount.incrementAndGet(); CREATE_COUNT.incrementAndGet();
log(statement); log(statement);
} }
public static void insert(String statement) { public static void insert(String statement) {
insertCount.incrementAndGet(); INSERT_COUNT.incrementAndGet();
log(statement); log(statement);
} }
public static void update(String statement) { public static void update(String statement) {
updateCount.incrementAndGet(); UPDATE_COUNT.incrementAndGet();
log(statement); log(statement);
} }
public static void merge(String statement) { public static void merge(String statement) {
mergeCount.incrementAndGet(); MERGE_COUNT.incrementAndGet();
log(statement); log(statement);
} }
public static void delete(String statement) { public static void delete(String statement) {
deleteCount.incrementAndGet(); DELETE_COUNT.incrementAndGet();
log(statement); log(statement);
} }
public static void select(String statement) { public static void select(String statement) {
selectCount.incrementAndGet(); SELECT_COUNT.incrementAndGet();
log(statement); log(statement);
} }
private static void log(String statement) { private static void log(String statement) {
if (logStatements) if (logStatements) {
out.println(statement); out.println(statement);
} }
}
public static void printStats() { public static void printStats() {
out.println("JaQu Runtime Stats"); out.println("JaQu Runtime Statistics");
out.println("======================="); out.println("=======================");
printStat("CREATE", createCount); printStat("CREATE", CREATE_COUNT);
printStat("INSERT", insertCount); printStat("INSERT", INSERT_COUNT);
printStat("UPDATE", updateCount); printStat("UPDATE", UPDATE_COUNT);
printStat("MERGE", mergeCount); printStat("MERGE", MERGE_COUNT);
printStat("DELETE", deleteCount); printStat("DELETE", DELETE_COUNT);
printStat("SELECT", selectCount); printStat("SELECT", SELECT_COUNT);
} }
private static void printStat(String name, AtomicLong value) { private static void printStat(String name, AtomicLong value) {
if (value.get() > 0) { if (value.get() > 0) {
DecimalFormat df = new DecimalFormat("###,###,###,###"); DecimalFormat df = new DecimalFormat("###,###,###,###");
out.println(name + "=" + df.format(createCount.get())); out.println(name + "=" + df.format(CREATE_COUNT.get()));
} }
} }
} }
\ No newline at end of file
...@@ -12,6 +12,8 @@ package org.h2.jaqu.util; ...@@ -12,6 +12,8 @@ package org.h2.jaqu.util;
*/ */
public class StringUtils { public class StringUtils {
private int todoDelete;
/** /**
* Replace all occurrences of the before string with the after string. * Replace all occurrences of the before string with the after string.
* *
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论