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

Cleanup:

- the dialect detection will most likely be based on the URL, not on the class name
- 'declaration' is a much too generic term for 'set column = value'
- method names should start with a verb (getTableName instead of tableName)
- remove redundancy and unnecessary formatting in Javadocs (keep it as simple as possible)
上级 991c3742
......@@ -56,11 +56,10 @@ public class Db {
public Db(Connection conn) {
this.conn = conn;
dialect = getDialect(conn.getClass().getCanonicalName());
dialect = getDialect(conn);
}
private SQLDialect getDialect(String clazz) {
int todo;
private SQLDialect getDialect(Connection conn) {
// TODO add special cases here
return new DefaultSQLDialect();
}
......@@ -155,7 +154,7 @@ public class Db {
Db upgradeDb() {
if (!upgradeChecked.contains(dbUpgrader.getClass())) {
// Flag as checked immediately because calls are nested.
// flag as checked immediately because calls are nested.
upgradeChecked.add(dbUpgrader.getClass());
JQDatabase model = dbUpgrader.getClass().getAnnotation(JQDatabase.class);
......@@ -165,16 +164,16 @@ public class Db {
// (SCHEMA="" && TABLE="") == DATABASE
from(v).where(v.schema).is("").and(v.table).is("").selectFirst();
if (dbVersion == null) {
// Database has no version registration, but model specifies
// version. Insert DbVersion entry and return.
// database has no version registration, but model specifies
// version: insert DbVersion entry and return.
DbVersion newDb = new DbVersion(model.version());
insert(newDb);
} else {
// Database has a version registration,
// database has a version registration:
// check to see if upgrade is required.
if ((model.version() > dbVersion.version)
&& (dbUpgrader != null)) {
// Database is an older version than model.
// database is an older version than the model
boolean success = dbUpgrader.upgradeDatabase(this,
dbVersion.version, model.version());
if (success) {
......@@ -190,29 +189,29 @@ public class Db {
<T> void upgradeTable(TableDefinition<T> model) {
if (!upgradeChecked.contains(model.getModelClass())) {
// Flag as checked immediately because calls are nested.
// flag is checked immediately because calls are nested
upgradeChecked.add(model.getModelClass());
if (model.tableVersion > 0) {
// Table is using JaQu version tracking.
// table is using JaQu version tracking.
DbVersion v = new DbVersion();
String schema = StringUtils.isNullOrEmpty(model.schemaName) ? "" : model.schemaName;
DbVersion dbVersion =
from(v).where(v.schema).like(schema).and(v.table)
.like(model.tableName).selectFirst();
if (dbVersion == null) {
// Table has no version registration, but model specifies
// version. Insert DbVersion entry and return.
// table has no version registration, but model specifies
// version: insert DbVersion entry
DbVersion newTable = new DbVersion(model.tableVersion);
newTable.schema = schema;
newTable.table = model.tableName;
insert(newTable);
} else {
// Table has a version registration.
// Check to see if upgrade is required.
// table has a version registration:
// check if upgrade is required
if ((model.tableVersion > dbVersion.version)
&& (dbUpgrader != null)) {
// Table is an older version than model.
// table is an older version than model
boolean success = dbUpgrader.upgradeTable(this, schema,
model.tableName, dbVersion.version, model.tableVersion);
if (success) {
......@@ -237,7 +236,7 @@ public class Db {
Table table = (Table) t;
Define.define(def, table);
} else if (clazz.isAnnotationPresent(JQTable.class)) {
// Annotated Class skips Define().define() static initializer
// annotated classes skip the Define().define() static initializer
T t = instance(clazz);
def.mapObject(t);
}
......
......@@ -32,7 +32,7 @@ public class Query<T> {
private Db db;
private SelectTable<T> from;
private ArrayList<Token> conditions = Utils.newArrayList();
private ArrayList<UpdateColumn> declarations = Utils.newArrayList();
private ArrayList<UpdateColumn> updateColumnDeclarations = Utils.newArrayList();
private ArrayList<SelectTable<?>> joins = Utils.newArrayList();
private final IdentityHashMap<Object, SelectColumn<T>> aliasMap = Utils.newIdentityHashMap();
private ArrayList<OrderExpression<T>> orderByList = Utils.newArrayList();
......@@ -122,17 +122,15 @@ public class Query<T> {
}
public <A> UpdateColumnSet<T, A> set(A field) {
int renameSetColumnClassToUpdateSetColumn;
return new UpdateColumnSet<T, A>(this, field);
}
public <A> UpdateColumnIncrement<T, A> increment(A field) {
int renameIncrementColumnClassToUpdateIncrementColumn;
return new UpdateColumnIncrement<T, A>(this, field);
}
public int update() {
if (declarations.size() == 0) {
if (updateColumnDeclarations.size() == 0) {
throw new RuntimeException("Missing set or increment call.");
}
SQLStatement stat = new SQLStatement(db);
......@@ -140,7 +138,7 @@ public class Query<T> {
from.appendSQL(stat);
stat.appendSQL(" SET ");
int i = 0;
for (UpdateColumn declaration : declarations) {
for (UpdateColumn declaration : updateColumnDeclarations) {
if (i++ > 0) {
stat.appendSQL(", ");
}
......@@ -329,9 +327,8 @@ public class Query<T> {
conditions.add(condition);
}
void addDeclarationToken(UpdateColumn declaration) {
int todoWhatIsDeclaration;
declarations.add(declaration);
void addUpdateColumnDeclaration(UpdateColumn declaration) {
updateColumnDeclarations.add(declaration);
}
void appendWhere(SQLStatement stat) {
......
......@@ -23,7 +23,7 @@ public interface SQLDialect {
* @param table the table name
* @return the SQL snippet
*/
String tableName(String schema, String table);
String getTableName(String schema, String table);
/**
* Get the CREATE INDEX statement.
......@@ -33,7 +33,7 @@ public interface SQLDialect {
* @param index the index definition
* @return the SQL statement
*/
String createIndex(String schema, String table, IndexDefinition index);
String getCreateIndex(String schema, String table, IndexDefinition index);
/**
* Append "LIMIT limit" to the SQL statement.
......@@ -51,20 +51,31 @@ public interface SQLDialect {
*/
void appendOffset(SQLStatement stat, long offset);
/**
* Whether memory tables are supported.
*
* @return true if they are
*/
boolean supportsMemoryTables();
/**
* Default implementation of an SQL dialect.
* Designed for an H2 database. May be suitable for others.
*/
public static class DefaultSQLDialect implements SQLDialect {
public String tableName(String schema, String table) {
public String getTableName(String schema, String table) {
if (StringUtils.isNullOrEmpty(schema)) {
return table;
}
return schema + "." + table;
}
public String createIndex(String schema, String table, IndexDefinition index) {
public boolean supportsMemoryTables() {
return true;
}
public String getCreateIndex(String schema, String table, IndexDefinition index) {
StatementBuilder buff = new StatementBuilder();
buff.append("CREATE ");
switch(index.type) {
......
......@@ -40,7 +40,7 @@ public class SQLStatement {
}
public SQLStatement appendTable(String schema, String table) {
return appendSQL(db.getDialect().tableName(schema, table));
return appendSQL(db.getDialect().getTableName(schema, table));
}
String getSQL() {
......
......@@ -79,7 +79,6 @@ class TableDefinition<T> {
void setValue(Object obj, Object o) {
try {
int setAccessibleShouldNotBeRequiredHere;
if (!field.isAccessible()) {
field.setAccessible(true);
}
......@@ -101,6 +100,7 @@ class TableDefinition<T> {
String schemaName;
String tableName;
int tableVersion;
private boolean createTableIfRequired = true;
private Class<T> clazz;
private ArrayList<FieldDefinition> fields = Utils.newArrayList();
......@@ -111,8 +111,6 @@ class TableDefinition<T> {
private ArrayList<IndexDefinition> indexes = Utils.newArrayList();
private boolean memoryTable;
int tableVersion;
TableDefinition(Class<T> clazz) {
this.clazz = clazz;
schemaName = null;
......@@ -275,13 +273,13 @@ class TableDefinition<T> {
}
/**
* Optionally truncates strings to maxLength
* Optionally truncates strings to the maximum length
*/
private Object getValue(Object obj, FieldDefinition field) {
Object value = field.getValue(obj);
if (field.trimString && field.maxLength > 0) {
if (value instanceof String) {
// Clip Strings
// clip strings
String s = (String) value;
if (s.length() > field.maxLength) {
return s.substring(0, field.maxLength);
......@@ -297,7 +295,7 @@ class TableDefinition<T> {
long insert(Db db, Object obj, boolean returnKey) {
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff = new StatementBuilder("INSERT INTO ");
buff.append(db.getDialect().tableName(schemaName, tableName)).append('(');
buff.append(db.getDialect().getTableName(schemaName, tableName)).append('(');
for (FieldDefinition field : fields) {
buff.appendExceptFirst(", ");
buff.append(field.columnName);
......@@ -326,7 +324,7 @@ class TableDefinition<T> {
}
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff = new StatementBuilder("MERGE INTO ");
buff.append(db.getDialect().tableName(schemaName, tableName)).append(" (");
buff.append(db.getDialect().getTableName(schemaName, tableName)).append(" (");
buff.resetCount();
for (FieldDefinition field : fields) {
buff.appendExceptFirst(", ");
......@@ -362,7 +360,7 @@ class TableDefinition<T> {
}
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(db.getDialect().tableName(schemaName, tableName)).append(" SET ");
buff.append(db.getDialect().getTableName(schemaName, tableName)).append(" SET ");
buff.resetCount();
for (FieldDefinition field : fields) {
......@@ -403,7 +401,7 @@ class TableDefinition<T> {
}
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff = new StatementBuilder("DELETE FROM ");
buff.append(db.getDialect().tableName(schemaName, tableName));
buff.append(db.getDialect().getTableName(schemaName, tableName));
buff.resetCount();
Object alias = Utils.newObject(obj.getClass());
Query<Object> query = Query.from(db, alias);
......@@ -429,44 +427,38 @@ class TableDefinition<T> {
TableDefinition<T> createTableIfRequired(Db db) {
if (!createTableIfRequired) {
// Skip table and index creation
// But still check for upgrades
// skip table and index creation
// but still check for upgrades
db.upgradeTable(this);
return this;
}
SQLDialect dialect = db.getDialect();
SQLStatement stat = new SQLStatement(db);
StatementBuilder buff;
if (memoryTable &&
db.getConnection().getClass()
.getCanonicalName().equals("org.h2.jdbc.JdbcConnection")) {
if (memoryTable && dialect.supportsMemoryTables()) {
buff = new StatementBuilder("CREATE MEMORY TABLE IF NOT EXISTS ");
} else {
buff = new StatementBuilder("CREATE TABLE IF NOT EXISTS ");
}
int todoChangeToGetTableNameChangeAllMethodsInDialectInterface;
buff.append(db.getDialect().tableName(schemaName, tableName)).append('(');
buff.append(dialect.getTableName(schemaName, tableName)).append('(');
for (FieldDefinition field : fields) {
buff.appendExceptFirst(", ");
buff.append(field.columnName).append(' ').append(field.dataType);
// FIELD LENGTH
if (field.maxLength > 0) {
buff.append('(').append(field.maxLength).append(')');
}
// AUTO_INCREMENT
if (field.isAutoIncrement) {
buff.append(" AUTO_INCREMENT");
}
// NOT NULL
if (!field.allowNull) {
buff.append(" NOT NULL");
}
// DEFAULT...
// default values
if (!field.isAutoIncrement && !field.isPrimaryKey) {
String dv = field.defaultValue;
if (!StringUtils.isNullOrEmpty(dv)) {
......@@ -478,8 +470,7 @@ class TableDefinition<T> {
}
}
int reviewJavadoc;
// PRIMARY KEY...
// primary key
if (primaryKeyColumnNames != null && primaryKeyColumnNames.size() > 0) {
buff.append(", PRIMARY KEY(");
buff.resetCount();
......@@ -494,24 +485,24 @@ class TableDefinition<T> {
StatementLogger.create(stat.getSQL());
stat.executeUpdate();
// Create Indexes
// create indexes
for (IndexDefinition index:indexes) {
String sql = db.getDialect().createIndex(schemaName, tableName, index);
String sql = db.getDialect().getCreateIndex(schemaName, tableName, index);
stat.setSQL(sql);
StatementLogger.create(stat.getSQL());
stat.executeUpdate();
}
// Table is created IF NOT EXISTS, otherwise statement is ignored
// But we still need to process potential Upgrade
// tables are created using IF NOT EXISTS
// but we may still need to upgrade
db.upgradeTable(this);
return this;
}
/**
* Retrieve list of columns from CSV whitespace notated index
* Retrieve list of columns from index definition.
*
* @param index the index columns
* @param index the index columns, separated by space
* @return the column list
*/
private List<String> getColumns(String index) {
......@@ -569,7 +560,7 @@ class TableDefinition<T> {
if (clazz.isAnnotationPresent(JQIndex.class)) {
JQIndex indexAnnotation = clazz.getAnnotation(JQIndex.class);
// Setup the indexes, if properly annotated
// setup the indexes, if properly annotated
addIndexes(IndexType.STANDARD, indexAnnotation.standard());
addIndexes(IndexType.UNIQUE, indexAnnotation.unique());
addIndexes(IndexType.HASH, indexAnnotation.hash());
......
......@@ -493,8 +493,7 @@ public class TableInspector {
JQColumn.class.getSimpleName(), fieldDef.isAutoIncrement,
col.isAutoIncrement)));
}
// last check
// default value...
// default value
if (!col.isAutoIncrement && !col.isPrimaryKey) {
// check Model.defaultValue format
if (!ModelUtils.isProperlyFormattedDefaultValue(fieldDef.defaultValue)) {
......@@ -510,20 +509,20 @@ public class TableInspector {
&& !isNullOrEmpty(col.defaultValue)) {
// Model.defaultValue is NULL, Column.defaultValue is NOT NULL
remarks.add(warn(table, col, format("{0}.defaultValue=\"\""
+ " while Column default=\"{1}\"",
+ " while column default=\"{1}\"",
JQColumn.class.getSimpleName(), col.defaultValue)));
} else if (!isNullOrEmpty(fieldDef.defaultValue)
&& isNullOrEmpty(col.defaultValue)) {
// Column.defaultValue is NULL, Model.defaultValue is NOT NULL
remarks.add(warn(table, col, format("{0}.defaultValue=\"{1}\""
+ " while Column default=\"\"",
+ " while column default=\"\"",
JQColumn.class.getSimpleName(), fieldDef.defaultValue)));
} else if (!isNullOrEmpty(fieldDef.defaultValue)
&& !isNullOrEmpty(col.defaultValue)) {
if (!fieldDef.defaultValue.equals(col.defaultValue)) {
// Model.defaultValue != Column.defaultValue
remarks.add(warn(table, col, format("{0}.defaultValue=\"{1}\""
+ " while Column default=\"{2}\"",
+ " while column default=\"{2}\"",
JQColumn.class.getSimpleName(), fieldDef.defaultValue,
col.defaultValue)));
}
......@@ -533,7 +532,7 @@ public class TableInspector {
if (!ModelUtils.isValidDefaultValue(fieldDef.field.getType(),
fieldDef.defaultValue)) {
remarks.add(error(table, col,
format("{0}.defaultValue=\"{1}\" is invalid!!",
format("{0}.defaultValue=\"{1}\" is invalid!",
JQColumn.class.getSimpleName(),
fieldDef.defaultValue)));
}
......
......@@ -25,7 +25,7 @@ public class UpdateColumnIncrement<T, A> implements UpdateColumn {
}
public Query<T> by(A y) {
query.addDeclarationToken(this);
query.addUpdateColumnDeclaration(this);
this.y = y;
return query;
}
......
......@@ -25,7 +25,7 @@ public class UpdateColumnSet<T, A> implements UpdateColumn {
}
public Query<T> to(A y) {
query.addDeclarationToken(this);
query.addUpdateColumnDeclaration(this);
this.y = y;
return query;
}
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论