static String getTypesSQL(@NonNull Container container) { StringBuilder builder = new StringBuilder(); Field[] fields = container.getFields(); FieldContainer primary = container.getPrimaryField(); if (primary == null) primary = getPrimaryFieldContainer(container); Field primaryField = null; if (primary != null) primaryField = primary.getField(); if (fields != null && fields.length > 0) { boolean isFirst = true; for (Field f : fields) { Ignore ignore = f.getAnnotation(Ignore.class); if (ignore != null) { LogUtil.d( CouSyncDb.TAG, CouSyncDb.LOG_HEADER + "ignore field=" + f.getName() + " when " + container.getModelName() + "create type column sql"); continue; } if (primaryField != null && f.equals(primaryField)) { LogUtil.d( CouSyncDb.TAG, CouSyncDb.LOG_HEADER + "jump primary key field=" + f.getName() + " when " + container.getModelName() + "create type column sql"); continue; } String typeSql = getTypeString(f); if (TextUtils.isEmpty(typeSql)) continue; if (isFirst) { isFirst = false; } else builder.append(Statement.COMMA); builder.append(typeSql); } } else { throw new NoFieldException(container.getModelName() + " have no field"); } return builder.toString(); }
/** 获得建表语句 */ public static String builder(Container container) { if (container == null) throw new IllegalArgumentException("CreateTableBuilder don't build sql with null"); StringBuilder builder = new StringBuilder(); builder.append(getTableSQL(container)); // create table if not exists name( String primaryKey = getPrimaryKeySQL(container); if (!TextUtils.isEmpty(primaryKey)) builder.append(primaryKey); // column type primary key autoincrement, else LogUtil.d( CouSyncDb.TAG, CouSyncDb.LOG_HEADER + container.getModelClass() + " discover no primary key when create table sql"); builder.append(getTypesSQL(container)); builder.append(Statement.BRACKET_RIGHT); builder.append(Statement.COLON); LogUtil.d(CouSyncDb.TAG, CouSyncDb.LOG_HEADER + " create table sql=" + builder.toString()); return builder.toString(); }
/** * column type, if boolean: column integer(1); * * @return null 不是基本类型 */ private static String getTypeString(@NonNull Field field) { String sql; Class clazz = field.getType(); String type = SqlUtil.getTypeOfClass(clazz); if (TextUtils.isEmpty(type)) { LogUtil.e( CouSyncDb.TAG, CouSyncDb.LOG_HEADER + field.getName() + "-" + field.getType() + " parse type error"); return null; } sql = field.getName() + type; if (clazz.equals(Boolean.class) || clazz.equals(boolean.class)) sql += Statement.BRACKET_LEFT + 1 + Statement.BRACKET_RIGHT; Unique unique = field.getAnnotation(Unique.class); if (unique != null) sql += Statement.UNIQUE; return sql; }