Search in sources :

Example 1 with BindTypeContext

use of com.abubusoft.kripton.processor.bind.BindTypeContext in project kripton by xcesco.

the class BindTableGenerator method visit.

private void visit(SQLiteDatabaseSchema schema, GeneratedTypeElement entity) throws Exception {
    int indexCounter = 0;
    // generate the class name that represents the table
    String classTableName = getTableClassName(entity.getSimpleName());
    PackageElement pkg = elementUtils.getPackageElement(entity.packageName);
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, classTableName);
    classBuilder = TypeSpec.classBuilder(classTableName).addModifiers(Modifier.PUBLIC).addSuperinterface(SQLiteTable.class);
    ;
    BindTypeContext context = new BindTypeContext(classBuilder, TypeUtility.typeName(packageName, classTableName), Modifier.STATIC, Modifier.PRIVATE);
    // javadoc for class
    classBuilder.addJavadoc("<p>");
    classBuilder.addJavadoc("\nEntity <code>$L</code> is associated to table <code>$L</code>\n", entity.getSimpleName(), entity.getTableName());
    classBuilder.addJavadoc("This class represents table associated to entity.\n");
    classBuilder.addJavadoc("</p>\n");
    JavadocUtility.generateJavadocGeneratedBy(classBuilder);
    classBuilder.addJavadoc(" @see $T\n", TypeUtility.className(entity.getName()));
    {
        // @formatter:off
        // table_name
        FieldSpec fieldSpec = FieldSpec.builder(String.class, "TABLE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("\"$L\"", entity.getTableName()).addJavadoc("Costant represents typeName of table $L\n", entity.getTableName()).build();
        classBuilder.addField(fieldSpec);
    // @formatter:on
    }
    StringBuilder bufferTable = new StringBuilder();
    StringBuilder bufferForeignKey = new StringBuilder();
    // shared between create table and drop table
    StringBuilder bufferIndexesCreate = new StringBuilder();
    StringBuilder bufferDropTable = new StringBuilder();
    StringBuilder bufferIndexesDrop = new StringBuilder();
    bufferTable.append("CREATE TABLE " + entity.getTableName());
    // define column typeName set
    String separator = "";
    bufferTable.append(" (");
    // for each column, that need to be persisted on table
    for (SQLProperty item : entity.getCollection()) {
        bufferTable.append(separator);
        bufferTable.append(item.columnName);
        // every column is a long
        bufferTable.append(" " + SQLTransformer.lookup(TypeName.LONG).getColumnTypeAsString());
        switch(item.columnType) {
            case PRIMARY_KEY:
                bufferTable.append(" PRIMARY KEY AUTOINCREMENT");
                break;
            case UNIQUE:
                bufferTable.append(" UNIQUE");
                break;
            case INDEXED:
                bufferIndexesCreate.append(String.format(" CREATE INDEX idx_%s_%s ON %s(%s);", entity.getTableName(), item.columnName, entity.getTableName(), item.columnName));
                bufferIndexesDrop.append(String.format(" DROP INDEX IF EXISTS idx_%s_%s;", entity.getTableName(), item.columnName));
                break;
            case STANDARD:
                break;
        }
        boolean nullable = item.isNullable();
        // null
        if (!nullable && item.columnType != ColumnType.PRIMARY_KEY) {
            bufferTable.append(" NOT NULL");
        }
        // foreign key
        String foreignClassName = item.foreignClassName;
        if (item.hasForeignKeyClassName()) {
            SQLiteEntity reference = model.getEntity(foreignClassName);
            if (reference == null) {
                // check if we have a DAO associated into DataSource
                // definition
                boolean found = false;
                for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
                    if (daoDefinition.getEntityClassName().equals(foreignClassName)) {
                        found = true;
                    }
                }
                if (!found) {
                    throw new NoDaoElementFound(schema, TypeUtility.className(foreignClassName));
                } else {
                    throw new InvalidBeanTypeException(item, foreignClassName);
                }
            }
            bufferForeignKey.append(", FOREIGN KEY(" + item.columnName + ") REFERENCES " + reference.getTableName() + "(" + reference.getPrimaryKey().columnName + ")");
            if (item.onDeleteAction != ForeignKeyAction.NO_ACTION) {
                bufferForeignKey.append(" ON DELETE " + item.onDeleteAction.toString().replaceAll("_", " "));
            }
            if (item.onUpdateAction != ForeignKeyAction.NO_ACTION) {
                bufferForeignKey.append(" ON UPDATE " + item.onUpdateAction.toString().replaceAll("_", " "));
            }
            // Same entity can not be own dependency.
            if (!entity.getClassName().equals(TypeUtility.typeName(reference.getElement()))) {
                entity.referedEntities.add(reference);
            }
        }
        separator = ", ";
    }
    // add foreign key
    bufferTable.append(bufferForeignKey.toString());
    bufferTable.append(");");
    // add indexes creation one table
    if (bufferIndexesCreate.length() > 0) {
        bufferTable.append(bufferIndexesCreate.toString());
    }
    // add single column indexes (NOT UNIQUE)
    {
        Pair<String, String> multiIndexes = buldIndexes(entity, false, indexCounter);
        if (!StringUtils.isEmpty(multiIndexes.value0)) {
            bufferTable.append(multiIndexes.value0 + ";");
            bufferIndexesDrop.append(multiIndexes.value1 + ";");
        }
    }
    {
        // create table SQL
        // @formatter:off
        FieldSpec.Builder fieldSpec = FieldSpec.builder(String.class, "CREATE_TABLE_SQL").addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC);
        // @formatter:on
        // @formatter:off
        fieldSpec.addJavadoc("<p>\nDDL to create table $L\n</p>\n", entity.getTableName());
        fieldSpec.addJavadoc("\n<pre>$L</pre>\n", bufferTable.toString());
        // @formatter:on
        classBuilder.addField(fieldSpec.initializer("$S", bufferTable.toString()).build());
    }
    // with tables
    if (bufferIndexesDrop.length() > 0) {
        bufferDropTable.append(bufferIndexesDrop.toString());
    }
    bufferDropTable.append("DROP TABLE IF EXISTS " + entity.getTableName() + ";");
    {
        // @formatter:off
        FieldSpec fieldSpec = FieldSpec.builder(String.class, "DROP_TABLE_SQL").addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC).initializer("$S", bufferDropTable.toString()).addJavadoc("<p>\nDDL to drop table $L\n</p>\n", entity.getTableName()).addJavadoc("\n<pre>$L</pre>\n", bufferDropTable.toString()).build();
        // @formatter:on
        classBuilder.addField(fieldSpec);
    }
    // define column typeName set
    for (ModelProperty item : entity.getCollection()) {
        item.accept(this);
    }
    ManagedPropertyPersistenceHelper.generateFieldPersistance(context, entity.getCollection(), PersistType.BYTE, true, Modifier.STATIC, Modifier.PUBLIC);
    model.sqlForCreate.add(bufferTable.toString());
    model.sqlForDrop.add(bufferDropTable.toString());
    generateColumnsArray(entity);
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : Builder(com.squareup.javapoet.FieldSpec.Builder) InvalidBeanTypeException(com.abubusoft.kripton.processor.exceptions.InvalidBeanTypeException) SQLiteTable(com.abubusoft.kripton.android.sqlite.SQLiteTable) BindTypeContext(com.abubusoft.kripton.processor.bind.BindTypeContext) FieldSpec(com.squareup.javapoet.FieldSpec) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) NoDaoElementFound(com.abubusoft.kripton.processor.exceptions.NoDaoElementFound) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ModelProperty(com.abubusoft.kripton.processor.core.ModelProperty) PackageElement(javax.lang.model.element.PackageElement) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) Pair(com.abubusoft.kripton.common.Pair) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 2 with BindTypeContext

use of com.abubusoft.kripton.processor.bind.BindTypeContext in project kripton by xcesco.

the class BindDaoBuilder method visit.

@Override
public void visit(SQLiteDaoDefinition value) throws Exception {
    currentDaoDefinition = value;
    // check if we need to generate or not
    if (value.getElement().getAnnotation(BindDaoMany2Many.class) != null && value.getElement().getAnnotation(BindGeneratedDao.class) == null) {
        return;
    }
    String classTableName = daoName(value);
    PackageElement pkg = elementUtils.getPackageOf(value.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDao.class, packageName, classTableName);
    builder = TypeSpec.classBuilder(classTableName).superclass(Dao.class).addSuperinterface(typeName(value.getElement())).addModifiers(Modifier.PUBLIC);
    for (TypeName item : value.implementedInterface) {
        builder.addSuperinterface(item);
    }
    BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(packageName, classTableName), Modifier.PRIVATE);
    String entityName = BindDataSourceSubProcessor.generateEntityName(value, value.getEntity());
    // javadoc for class
    builder.addJavadoc("<p>");
    builder.addJavadoc("\nDAO implementation for entity <code>$L</code>, based on interface <code>$L</code>\n", entityName, value.getElement().getSimpleName().toString());
    builder.addJavadoc("</p>\n\n");
    JavadocUtility.generateJavadocGeneratedBy(builder);
    builder.addJavadoc(" @see $T\n", TypeUtility.className(value.getEntityClassName()));
    builder.addJavadoc(" @see $T\n", TypeUtility.className(value.getElement().getQualifiedName().toString()));
    builder.addJavadoc(" @see $T\n", BindTableGenerator.tableClassName(value, value.getEntity()));
    {
        // constructor
        MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameter(SQLContext.class, "context");
        methodBuilder.addStatement("super(context)");
        builder.addMethod(methodBuilder.build());
    }
    // define column typeName set
    for (SQLiteModelMethod item : value.getCollection()) {
        item.accept(this);
    }
    // generate live data support methods
    if (value.hasLiveData()) {
        // method sendEvent
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_REGISTRY_EVENT).addModifiers(Modifier.PROTECTED).addParameter(Integer.TYPE, "affectedRows");
            methodBuilder.beginControlFlow("if (affectedRows==0)");
            methodBuilder.addStatement("return");
            methodBuilder.endControlFlow();
            methodBuilder.beginControlFlow("if (_context.isInSession())");
            methodBuilder.addStatement("_context.registrySQLEvent($T.$L)", BindDataSourceBuilder.generateDataSourceName(value.getParent()), value.daoUidName);
            methodBuilder.nextControlFlow("else");
            methodBuilder.addStatement("invalidateLiveData()");
            methodBuilder.endControlFlow();
            builder.addMethod(methodBuilder.build());
        }
        // field liveDatas
        {
            FieldSpec.Builder liveDataBuilder = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Collection.class), ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class)))), "liveDatas").addModifiers(Modifier.STATIC).initializer(CodeBlock.builder().add("$T.synchronizedCollection(new $T())", Collections.class, ParameterizedTypeName.get(ClassName.get(HashSet.class), ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))))).build());
            builder.addField(liveDataBuilder.build());
        }
        // registryLiveData
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_REGISTRY_LIVE_DATA).addModifiers(Modifier.PROTECTED).addParameter(ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class)), "value");
            methodBuilder.addStatement("liveDatas.add(new $T(value))", ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))));
            builder.addMethod(methodBuilder.build());
        }
        // invalidateLiveData
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_INVALIDATE_LIVE_DATA).addModifiers(Modifier.PROTECTED);
            methodBuilder.beginControlFlow("for ($T item: liveDatas)", ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))));
            methodBuilder.beginControlFlow("if (item.get()!=null)");
            methodBuilder.addStatement("item.get().invalidate()");
            methodBuilder.endControlFlow();
            methodBuilder.endControlFlow();
            builder.addMethod(methodBuilder.build());
        }
    }
    // generate serializer params
    for (Entry<TypeName, String> item : currentDaoDefinition.managedParams.entrySet()) {
        ManagedPropertyPersistenceHelper.generateParamSerializer(context, item.getValue(), item.getKey(), PersistType.BYTE);
        ManagedPropertyPersistenceHelper.generateParamParser(context, item.getValue(), item.getKey(), PersistType.BYTE);
    }
    // generate subject
    if (currentDaoDefinition.getParent().generateRx) {
        ParameterizedTypeName subjectTypeName = ParameterizedTypeName.get(ClassName.get(PublishSubject.class), ClassName.get(SQLiteEvent.class));
        // subject
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("subject").addModifiers(Modifier.PUBLIC);
        methodBuilder.addStatement("return subject").returns(subjectTypeName);
        builder.addMethod(methodBuilder.build());
        // subject instance
        FieldSpec.Builder fieldBuilder = FieldSpec.builder(subjectTypeName, "subject", Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC).initializer("$T.create()", ClassName.get(PublishSubject.class));
        builder.addField(fieldBuilder.build());
    }
    // generate prepared statement cleaner
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("clearCompiledStatements").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(Void.TYPE);
        for (String item : value.preparedStatementNames) {
            methodBuilder.beginControlFlow("if ($L!=null)", item);
            methodBuilder.addStatement("$L.close()", item);
            methodBuilder.addStatement("$L=null", item);
            methodBuilder.endControlFlow();
        }
        builder.addMethod(methodBuilder.build());
    }
    TypeSpec typeSpec = builder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) Builder(com.squareup.javapoet.TypeSpec.Builder) BindTypeContext(com.abubusoft.kripton.processor.bind.BindTypeContext) FieldSpec(com.squareup.javapoet.FieldSpec) SQLiteEvent(com.abubusoft.kripton.android.sqlite.SQLiteEvent) BindDao(com.abubusoft.kripton.android.annotation.BindDao) Dao(com.abubusoft.kripton.android.sqlite.Dao) BindGeneratedDao(com.abubusoft.kripton.android.annotation.BindGeneratedDao) SQLiteModelMethod(com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod) PublishSubject(io.reactivex.subjects.PublishSubject) WeakReference(java.lang.ref.WeakReference) Collection(java.util.Collection) KriptonComputableLiveData(com.abubusoft.kripton.android.sqlite.livedata.KriptonComputableLiveData) PackageElement(javax.lang.model.element.PackageElement) Collections(java.util.Collections) SQLContext(com.abubusoft.kripton.android.sqlite.SQLContext) HashSet(java.util.HashSet) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 3 with BindTypeContext

use of com.abubusoft.kripton.processor.bind.BindTypeContext in project kripton by xcesco.

the class BindSharedPreferencesBuilder method generate.

/**
 * Generate shared preference manager
 *
 * @return typeName of generated class
 *
 * @throws IOException
 */
public static String generate(Elements elementUtils, Filer filer, PrefsEntity entity) throws IOException {
    com.abubusoft.kripton.common.Converter<String, String> converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
    String beanClassName = entity.getSimpleName().toString();
    String suffix;
    if (beanClassName.endsWith(SUFFIX_SHARED_PREFERENCE)) {
        suffix = "";
    } else if (beanClassName.endsWith(SUFFIX_PREFERENCE)) {
        suffix = "";
    } else {
        suffix = SUFFIX_SHARED_PREFERENCE;
    }
    String className = PREFIX + beanClassName + suffix;
    ModelAnnotation annotation = entity.getAnnotation(BindSharedPreferences.class);
    String sharedPreferenceName = annotation.getAttribute(AnnotationAttributeType.VALUE);
    PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindSharedPreferences.class, packageName, className);
    // @formatter:off
    builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).superclass(AbstractSharedPreference.class);
    BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(entity.getElement()), Modifier.PRIVATE);
    // @formatter:on
    builder.addJavadoc("This class is the shared preference binder defined for $T\n\n", entity.getElement());
    JavadocUtility.generateJavadocGeneratedBy(builder);
    builder.addJavadoc("@see $T\n", entity.getElement());
    if (StringUtils.hasText(sharedPreferenceName)) {
        builder.addField(FieldSpec.builder(String.class, "SHARED_PREFERENCE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("$S", converter.convert(entity.getSimpleName().toString())).addJavadoc("shared preferences typeName for $T\n", entity.getElement()).build());
    }
    builder.addField(FieldSpec.builder(className(beanClassName), "defaultBean", Modifier.PRIVATE, Modifier.FINAL).addJavadoc("working instance of bean\n").build());
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("edit").addJavadoc("create an editor to modify shared preferences\n").returns(typeName("BindEditor")).addModifiers(Modifier.PUBLIC);
        methodBuilder.addStatement("return new $T()", typeName("BindEditor"));
        builder.addMethod(methodBuilder.build());
    }
    generateEditor(entity);
    generateConstructor(sharedPreferenceName, beanClassName);
    generateRefresh(sharedPreferenceName, className);
    generateResetMethod(entity);
    generateReadMethod(entity);
    generateWriteMethod(entity);
    generateSingleReadMethod(entity);
    // generate all needed writer and reader
    List<PrefsProperty> fields = entity.getCollection();
    List<PrefsProperty> filteredFields = new ArrayList<>();
    // we need to avoid generation of persists values
    for (PrefsProperty item : fields) {
        if (SetPrefsTransformation.isStringSet(item)) {
            continue;
        } else {
            filteredFields.add(item);
        }
    }
    // avoid to consider StringSet
    ManagedPropertyPersistenceHelper.generateFieldPersistance(context, filteredFields, PersistType.STRING, false, Modifier.PROTECTED);
    generateInstance(className);
    TypeSpec typeSpec = builder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
    return className;
}
Also used : Builder(com.squareup.javapoet.TypeSpec.Builder) ArrayList(java.util.ArrayList) BindTypeContext(com.abubusoft.kripton.processor.bind.BindTypeContext) AbstractSharedPreference(com.abubusoft.kripton.android.sharedprefs.AbstractSharedPreference) ModelAnnotation(com.abubusoft.kripton.processor.core.ModelAnnotation) PrefsProperty(com.abubusoft.kripton.processor.sharedprefs.model.PrefsProperty) PackageElement(javax.lang.model.element.PackageElement) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 4 with BindTypeContext

use of com.abubusoft.kripton.processor.bind.BindTypeContext in project kripton by xcesco.

the class BindTableGenerator method visit.

@Override
public void visit(SQLiteDatabaseSchema schema, SQLiteEntity entity) throws Exception {
    int indexCounter = 0;
    // generate the class name that represents the table
    String classTableName = getTableClassName(entity.getSimpleName());
    PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, classTableName);
    classBuilder = TypeSpec.classBuilder(classTableName).addModifiers(Modifier.PUBLIC).addSuperinterface(SQLiteTable.class);
    BindTypeContext context = new BindTypeContext(classBuilder, TypeUtility.typeName(packageName, classTableName), Modifier.STATIC, Modifier.PRIVATE);
    // javadoc for class
    classBuilder.addJavadoc("<p>");
    classBuilder.addJavadoc("\nEntity <code>$L</code> is associated to table <code>$L</code>\n", entity.getSimpleName(), entity.getTableName());
    classBuilder.addJavadoc("This class represents table associated to entity.\n");
    classBuilder.addJavadoc("</p>\n");
    JavadocUtility.generateJavadocGeneratedBy(classBuilder);
    classBuilder.addJavadoc(" @see $T\n", TypeUtility.className(entity.getName()));
    {
        // @formatter:off
        // table_name
        FieldSpec fieldSpec = FieldSpec.builder(String.class, "TABLE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("\"$L\"", entity.getTableName()).addJavadoc("Costant represents typeName of table $L\n", entity.getTableName()).build();
        classBuilder.addField(fieldSpec);
    // @formatter:on
    }
    StringBuilder bufferTable = new StringBuilder();
    StringBuilder bufferForeignKey = new StringBuilder();
    // shared between create table and drop table
    StringBuilder bufferIndexesCreate = new StringBuilder();
    StringBuilder bufferDropTable = new StringBuilder();
    StringBuilder bufferIndexesDrop = new StringBuilder();
    bufferTable.append("CREATE TABLE " + entity.getTableName());
    // define column typeName set
    String separator = "";
    bufferTable.append(" (");
    // for each column, that need to be persisted on table
    for (SQLProperty item : entity.getCollection()) {
        bufferTable.append(separator);
        bufferTable.append(item.columnName);
        bufferTable.append(" " + SQLTransformer.columnTypeAsString(item));
        switch(item.columnType) {
            case PRIMARY_KEY:
                bufferTable.append(" PRIMARY KEY AUTOINCREMENT");
                break;
            case UNIQUE:
                bufferTable.append(" UNIQUE");
                break;
            case INDEXED:
                bufferIndexesCreate.append(String.format(" CREATE INDEX idx_%s_%s ON %s(%s);", entity.getTableName(), item.columnName, entity.getTableName(), item.columnName));
                bufferIndexesDrop.append(String.format(" DROP INDEX IF EXISTS idx_%s_%s;", entity.getTableName(), item.columnName));
                break;
            case STANDARD:
                break;
        }
        boolean nullable = item.isNullable();
        // null
        if (!nullable && item.columnType != ColumnType.PRIMARY_KEY) {
            bufferTable.append(" NOT NULL");
        }
        // foreign key
        String foreignClassName = item.foreignClassName;
        if (item.hasForeignKeyClassName()) {
            SQLiteEntity reference = model.getEntity(foreignClassName);
            if (reference == null) {
                // check if we have a DAO associated into DataSource
                // definition
                boolean found = false;
                for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
                    if (daoDefinition.getEntityClassName().equals(foreignClassName)) {
                        found = true;
                    }
                }
                if (!found) {
                    throw new NoDaoElementFound(schema, TypeUtility.className(foreignClassName));
                } else {
                    throw new InvalidBeanTypeException(item, foreignClassName);
                }
            }
            // long/Long
            if (!TypeUtility.isTypeIncludedIn(item.getPropertyType().getTypeName(), Long.class, Long.TYPE)) {
                throw new InvalidForeignKeyTypeException(item);
            }
            bufferForeignKey.append(", FOREIGN KEY(" + item.columnName + ") REFERENCES " + reference.getTableName() + "(" + reference.getPrimaryKey().columnName + ")");
            if (item.onDeleteAction != ForeignKeyAction.NO_ACTION) {
                bufferForeignKey.append(" ON DELETE " + item.onDeleteAction.toString().replaceAll("_", " "));
            }
            if (item.onUpdateAction != ForeignKeyAction.NO_ACTION) {
                bufferForeignKey.append(" ON UPDATE " + item.onUpdateAction.toString().replaceAll("_", " "));
            }
            // Same entity can not be own dependency.
            if (!entity.equals(reference)) {
                entity.referedEntities.add(reference);
            }
        }
        separator = ", ";
    }
    // add foreign key
    bufferTable.append(bufferForeignKey.toString());
    bufferTable.append(");");
    // add indexes creation one table
    if (bufferIndexesCreate.length() > 0) {
        bufferTable.append(bufferIndexesCreate.toString());
    }
    // add multicolumn indexes (UNIQUE)
    {
        Pair<String, String> multiIndexes = buldIndexes(entity, true, indexCounter);
        if (!StringUtils.isEmpty(multiIndexes.value0)) {
            bufferTable.append(multiIndexes.value0 + ";");
            bufferIndexesDrop.append(multiIndexes.value1 + ";");
        }
    }
    // add multicolumn indexes (NOT UNIQUE)
    {
        Pair<String, String> multiIndexes = buldIndexes(entity, false, indexCounter);
        if (!StringUtils.isEmpty(multiIndexes.value0)) {
            bufferTable.append(multiIndexes.value0 + ";");
            bufferIndexesDrop.append(multiIndexes.value1 + ";");
        }
    }
    {
        // create table SQL
        // @formatter:off
        FieldSpec.Builder fieldSpec = FieldSpec.builder(String.class, "CREATE_TABLE_SQL").addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC);
        // @formatter:on
        // @formatter:off
        fieldSpec.addJavadoc("<p>\nDDL to create table $L\n</p>\n", entity.getTableName());
        fieldSpec.addJavadoc("\n<pre>$L</pre>\n", bufferTable.toString());
        // @formatter:on
        classBuilder.addField(fieldSpec.initializer("$S", bufferTable.toString()).build());
    }
    // with tables
    if (bufferIndexesDrop.length() > 0) {
        bufferDropTable.append(bufferIndexesDrop.toString());
    }
    bufferDropTable.append("DROP TABLE IF EXISTS " + entity.getTableName() + ";");
    {
        // @formatter:off
        FieldSpec fieldSpec = FieldSpec.builder(String.class, "DROP_TABLE_SQL").addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC).initializer("$S", bufferDropTable.toString()).addJavadoc("<p>\nDDL to drop table $L\n</p>\n", entity.getTableName()).addJavadoc("\n<pre>$L</pre>\n", bufferDropTable.toString()).build();
        // @formatter:on
        classBuilder.addField(fieldSpec);
    }
    // define column typeName set
    for (ModelProperty item : entity.getCollection()) {
        item.accept(this);
    }
    ManagedPropertyPersistenceHelper.generateFieldPersistance(context, entity.getCollection(), PersistType.BYTE, true, Modifier.STATIC, Modifier.PUBLIC);
    model.sqlForCreate.add(bufferTable.toString());
    model.sqlForDrop.add(bufferDropTable.toString());
    generateColumnsArray(entity);
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : InvalidForeignKeyTypeException(com.abubusoft.kripton.processor.exceptions.InvalidForeignKeyTypeException) Builder(com.squareup.javapoet.FieldSpec.Builder) InvalidBeanTypeException(com.abubusoft.kripton.processor.exceptions.InvalidBeanTypeException) SQLiteTable(com.abubusoft.kripton.android.sqlite.SQLiteTable) BindTypeContext(com.abubusoft.kripton.processor.bind.BindTypeContext) FieldSpec(com.squareup.javapoet.FieldSpec) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) NoDaoElementFound(com.abubusoft.kripton.processor.exceptions.NoDaoElementFound) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ModelProperty(com.abubusoft.kripton.processor.core.ModelProperty) PackageElement(javax.lang.model.element.PackageElement) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) Pair(com.abubusoft.kripton.common.Pair) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

BindTypeContext (com.abubusoft.kripton.processor.bind.BindTypeContext)4 TypeSpec (com.squareup.javapoet.TypeSpec)4 PackageElement (javax.lang.model.element.PackageElement)4 FieldSpec (com.squareup.javapoet.FieldSpec)3 SQLiteTable (com.abubusoft.kripton.android.sqlite.SQLiteTable)2 Pair (com.abubusoft.kripton.common.Pair)2 ModelProperty (com.abubusoft.kripton.processor.core.ModelProperty)2 InvalidBeanTypeException (com.abubusoft.kripton.processor.exceptions.InvalidBeanTypeException)2 NoDaoElementFound (com.abubusoft.kripton.processor.exceptions.NoDaoElementFound)2 SQLProperty (com.abubusoft.kripton.processor.sqlite.model.SQLProperty)2 SQLiteDaoDefinition (com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)2 SQLiteEntity (com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)2 Builder (com.squareup.javapoet.FieldSpec.Builder)2 Builder (com.squareup.javapoet.TypeSpec.Builder)2 BindDao (com.abubusoft.kripton.android.annotation.BindDao)1 BindGeneratedDao (com.abubusoft.kripton.android.annotation.BindGeneratedDao)1 AbstractSharedPreference (com.abubusoft.kripton.android.sharedprefs.AbstractSharedPreference)1 Dao (com.abubusoft.kripton.android.sqlite.Dao)1 SQLContext (com.abubusoft.kripton.android.sqlite.SQLContext)1 SQLiteEvent (com.abubusoft.kripton.android.sqlite.SQLiteEvent)1