Search in sources :

Example 16 with SQLiteEntity

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity in project kripton by xcesco.

the class BindDataSourceBuilder method generateOnCreate.

/**
 * @param schema
 * @param orderedEntities
 */
private boolean generateOnCreate(SQLiteDatabaseSchema schema, List<SQLiteEntity> orderedEntities) {
    boolean useForeignKey = false;
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onCreate").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
    methodBuilder.addParameter(SQLiteDatabase.class, "database");
    methodBuilder.addJavadoc("onCreate\n");
    methodBuilder.addCode("// generate tables\n");
    if (schema.isLogEnabled()) {
        // generate log section - BEGIN
        methodBuilder.addComment("log section BEGIN");
        methodBuilder.beginControlFlow("if (this.logEnabled)");
        methodBuilder.beginControlFlow("if (options.inMemory)");
        methodBuilder.addStatement("$T.info(\"Create database in memory\")", Logger.class);
        methodBuilder.nextControlFlow("else");
        methodBuilder.addStatement("$T.info(\"Create database '%s' version %s\",this.name, this.version)", Logger.class);
        methodBuilder.endControlFlow();
        // generate log section - END
        methodBuilder.endControlFlow();
        methodBuilder.addComment("log section END");
    }
    for (SQLiteEntity item : orderedEntities) {
        if (schema.isLogEnabled()) {
            // generate log section - BEGIN
            methodBuilder.addComment("log section BEGIN");
            methodBuilder.beginControlFlow("if (this.logEnabled)");
            methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class, BindTableGenerator.tableClassName(null, item));
            // generate log section - END
            methodBuilder.endControlFlow();
            methodBuilder.addComment("log section END");
        }
        methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)", BindTableGenerator.tableClassName(null, item));
        if (item.referedEntities.size() > 0) {
            useForeignKey = true;
        }
    }
    // if we have generated entities, we use foreign key for sure
    if (schema.generatedEntities.size() > 0)
        useForeignKey = true;
    for (GeneratedTypeElement item : schema.generatedEntities) {
        if (schema.isLogEnabled()) {
            // generate log section - BEGIN
            methodBuilder.addComment("log section BEGIN");
            methodBuilder.beginControlFlow("if (this.logEnabled)");
            methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class, TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
            // generate log section - END
            methodBuilder.endControlFlow();
            methodBuilder.addComment("log section END");
        }
        methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)", TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
    }
    methodBuilder.beginControlFlow("if (options.databaseLifecycleHandler != null)");
    methodBuilder.addStatement("options.databaseLifecycleHandler.onCreate(database)");
    methodBuilder.endControlFlow();
    methodBuilder.addStatement("justCreated=true");
    classBuilder.addMethod(methodBuilder.build());
    return useForeignKey;
}
Also used : GeneratedTypeElement(com.abubusoft.kripton.processor.element.GeneratedTypeElement) MethodSpec(com.squareup.javapoet.MethodSpec) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)

Example 17 with SQLiteEntity

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity in project kripton by xcesco.

the class BindDataSourceBuilder method generateOnUpgrade.

/**
 * @param schema
 * @param orderedEntities
 */
private void generateOnUpgrade(SQLiteDatabaseSchema schema, List<SQLiteEntity> orderedEntities) {
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onUpgrade").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
    methodBuilder.addParameter(SQLiteDatabase.class, "database");
    methodBuilder.addParameter(Integer.TYPE, "previousVersion");
    methodBuilder.addParameter(Integer.TYPE, "currentVersion");
    methodBuilder.addJavadoc("onUpgrade\n");
    Collections.reverse(orderedEntities);
    if (schema.isLogEnabled()) {
        // generate log section - BEGIN
        methodBuilder.addComment("log section BEGIN");
        methodBuilder.beginControlFlow("if (this.logEnabled)");
        methodBuilder.addStatement("$T.info(\"Update database '%s' from version %s to version %s\",this.name, previousVersion, currentVersion)", Logger.class);
        // generate log section - END
        methodBuilder.endControlFlow();
        methodBuilder.addComment("log section END");
    }
    methodBuilder.addComment("if we have a list of update task, try to execute them");
    methodBuilder.beginControlFlow("if (options.updateTasks != null)");
    methodBuilder.addStatement("$T<$T> tasks = buildTaskList(previousVersion, currentVersion)", List.class, SQLiteUpdateTask.class);
    methodBuilder.beginControlFlow("for ($T task : tasks)", SQLiteUpdateTask.class);
    // generate log section - BEGIN
    methodBuilder.addComment("log section BEGIN");
    methodBuilder.beginControlFlow("if (this.logEnabled)");
    methodBuilder.addStatement("$T.info(\"Begin update database from version %s to %s\", previousVersion, previousVersion+1)", Logger.class);
    // generate log section - END
    methodBuilder.endControlFlow();
    methodBuilder.addComment("log section END");
    methodBuilder.addStatement("task.execute(database, previousVersion, previousVersion+1)");
    // generate log section - BEGIN
    methodBuilder.addComment("log section BEGIN");
    methodBuilder.beginControlFlow("if (this.logEnabled)");
    methodBuilder.addStatement("$T.info(\"End update database from version %s to %s\", previousVersion, previousVersion+1)", Logger.class);
    // generate log section - END
    methodBuilder.endControlFlow();
    methodBuilder.addComment("log section END");
    methodBuilder.addStatement("previousVersion++");
    methodBuilder.endControlFlow();
    methodBuilder.nextControlFlow("else");
    methodBuilder.addComment("drop all tables");
    methodBuilder.addStatement("$T.dropTablesAndIndices(database)", SQLiteUpdateTaskHelper.class);
    // reorder entities
    Collections.reverse(orderedEntities);
    methodBuilder.addCode("\n");
    methodBuilder.addCode("// generate tables\n");
    for (SQLiteEntity item : orderedEntities) {
        if (schema.isLogEnabled()) {
            // generate log section - BEGIN
            methodBuilder.addComment("log section BEGIN");
            methodBuilder.beginControlFlow("if (this.logEnabled)");
            methodBuilder.addCode("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL);\n", Logger.class, BindTableGenerator.tableClassName(null, item));
            // generate log section - END
            methodBuilder.endControlFlow();
            methodBuilder.addComment("log section END");
        }
        methodBuilder.addCode("database.execSQL($T.CREATE_TABLE_SQL);\n", BindTableGenerator.tableClassName(null, item));
    }
    // use generated entities too
    for (GeneratedTypeElement item : schema.generatedEntities) {
        if (schema.isLogEnabled()) {
            // generate log section - BEGIN
            methodBuilder.addComment("log section BEGIN");
            methodBuilder.beginControlFlow("if (this.logEnabled)");
            methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class, TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
            // generate log section - END
            methodBuilder.endControlFlow();
            methodBuilder.addComment("log section END");
        }
        methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)", TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
    }
    methodBuilder.endControlFlow();
    methodBuilder.beginControlFlow("if (options.databaseLifecycleHandler != null)");
    methodBuilder.addStatement("options.databaseLifecycleHandler.onUpdate(database, previousVersion, currentVersion, true)");
    methodBuilder.endControlFlow();
    classBuilder.addMethod(methodBuilder.build());
}
Also used : GeneratedTypeElement(com.abubusoft.kripton.processor.element.GeneratedTypeElement) MethodSpec(com.squareup.javapoet.MethodSpec) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)

Example 18 with SQLiteEntity

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity in project kripton by xcesco.

the class BindDataSourceBuilder method buildDataSource.

public void buildDataSource(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema, String daoFactoryName) throws Exception {
    ClassName daoFactoryClazz = className(daoFactoryName);
    Converter<String, String> convert = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
    ClassName dataSourceClassName = generateDataSourceName(schema);
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, dataSourceClassName);
    classBuilder = TypeSpec.classBuilder(dataSourceClassName.simpleName()).addModifiers(Modifier.PUBLIC).superclass(AbstractDataSource.class).addSuperinterface(daoFactoryClazz).addSuperinterface(TypeUtility.typeName(schema.getElement().asType()));
    classBuilder.addJavadoc("<p>\n");
    classBuilder.addJavadoc("Represents implementation of datasource $L.\n", schema.getName());
    classBuilder.addJavadoc("This class expose database interface through Dao attribute.\n", schema.getName());
    classBuilder.addJavadoc("</p>\n\n");
    JavadocUtility.generateJavadocGeneratedBy(classBuilder);
    classBuilder.addJavadoc("@see $T\n", className(schema.getName()));
    classBuilder.addJavadoc("@see $T\n", daoFactoryClazz);
    for (SQLiteDaoDefinition dao : schema.getCollection()) {
        TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);
        classBuilder.addJavadoc("@see $T\n", dao.getElement());
        classBuilder.addJavadoc("@see $T\n", daoImplName);
        String entity = BindDataSourceSubProcessor.generateEntityName(dao, dao.getEntity());
        classBuilder.addJavadoc("@see $T\n", TypeUtility.typeName(entity));
    }
    // define static fields
    // instance
    classBuilder.addField(FieldSpec.builder(dataSourceClassName, "instance", Modifier.STATIC, Modifier.VOLATILE).addJavadoc("<p>datasource singleton</p>\n").build());
    classBuilder.addField(FieldSpec.builder(Object.class, "mutex", Modifier.STATIC, Modifier.FINAL, Modifier.PRIVATE).addJavadoc("<p>Mutex to manage multithread access to instance</p>\n").initializer("new Object()").build());
    for (SQLiteDaoDefinition dao : schema.getCollection()) {
        // TypeName daoInterfaceName =
        // BindDaoBuilder.daoInterfaceTypeName(dao);
        TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);
        classBuilder.addField(FieldSpec.builder(daoImplName, convert.convert(dao.getName()), Modifier.PROTECTED).addJavadoc("<p>dao instance</p>\n").initializer("new $T(context)", daoImplName).build());
        // dao with connections
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("get" + dao.getName()).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(BindDaoBuilder.daoTypeName(dao));
            methodBuilder.addCode("return $L;\n", convert.convert(dao.getName()));
            classBuilder.addMethod(methodBuilder.build());
        }
    }
    if (schema.generateRx) {
        generateRx(dataSourceClassName, daoFactoryName);
        for (SQLiteDaoDefinition dao : schema.getCollection()) {
            // subject
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, dao.getEntitySimplyClassName() + "Subject")).addModifiers(Modifier.PUBLIC);
            methodBuilder.addStatement("return $L.subject()", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, convert.convert(dao.getName()))).returns(ParameterizedTypeName.get(PublishSubject.class, SQLiteEvent.class));
            classBuilder.addMethod(methodBuilder.build());
        }
    }
    // interface
    generateMethodExecuteTransaction(daoFactoryName);
    generateMethodExecuteBatch(daoFactoryName);
    // generate instance
    generateInstanceOrBuild(schema, dataSourceClassName.simpleName(), true);
    // generate open
    generateOpen(dataSourceClassName.simpleName());
    // generate openReadOnly
    generateOpenReadOnly(dataSourceClassName.simpleName());
    // generate constructor
    generateConstructor(schema);
    // before use entities, order them with dependencies respect
    List<SQLiteEntity> orderedEntities = generateOrderedEntitiesList(schema);
    // onCreate
    boolean useForeignKey = generateOnCreate(schema, orderedEntities);
    // onUpgrade
    generateOnUpgrade(schema, orderedEntities);
    // onConfigure
    generateOnConfigure(useForeignKey);
    // generate
    generateDaoUids(classBuilder, schema);
    // 
    // generate prepared statement cleaner
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("clearCompiledStatements").addModifiers(Modifier.PUBLIC).returns(Void.TYPE);
        for (SQLiteDaoDefinition dao : schema.getCollection()) {
            methodBuilder.addStatement("$T.clearCompiledStatements()", TypeUtility.className(dao.getElement().getQualifiedName().toString() + "Impl"));
        }
        classBuilder.addMethod(methodBuilder.build());
    }
    // generate single thread datasource
    generateDataSourceSingleThread(schema, dataSourceClassName.simpleName());
    // generate build
    generateInstanceOrBuild(schema, dataSourceClassName.simpleName(), false);
    {
        Builder f = FieldSpec.builder(ArrayTypeName.of(SQLiteTable.class), "TABLES", Modifier.FINAL, Modifier.STATIC).addJavadoc("List of tables compose datasource\n");
        com.squareup.javapoet.CodeBlock.Builder c = CodeBlock.builder();
        String s = "";
        c.add("{");
        for (SQLiteEntity entity : schema.getEntities()) {
            String tableName = BindTableGenerator.getTableClassName(entity.getName());
            c.add(s + "new $T()", TypeUtility.className(tableName));
            s = ", ";
        }
        for (GeneratedTypeElement entity : schema.generatedEntities) {
            String tableName = BindTableGenerator.getTableClassName(entity.getQualifiedName());
            c.add(s + "new $T()", TypeUtility.className(tableName));
            s = ", ";
        }
        c.add("}");
        f.initializer(c.build());
        classBuilder.addField(f.build());
        classBuilder.addMethod(MethodSpec.methodBuilder("tables").addJavadoc("List of tables compose datasource:\n").addModifiers(Modifier.PUBLIC, Modifier.STATIC).addStatement("return TABLES").returns(ArrayTypeName.of(SQLiteTable.class)).build());
    }
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, dataSourceClassName.packageName(), typeSpec);
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) MethodSpec(com.squareup.javapoet.MethodSpec) Builder(com.squareup.javapoet.FieldSpec.Builder) SQLiteTable(com.abubusoft.kripton.android.sqlite.SQLiteTable) AbstractDataSource(com.abubusoft.kripton.android.sqlite.AbstractDataSource) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) SQLiteEvent(com.abubusoft.kripton.android.sqlite.SQLiteEvent) GeneratedTypeElement(com.abubusoft.kripton.processor.element.GeneratedTypeElement) PublishSubject(io.reactivex.subjects.PublishSubject) ClassName(com.squareup.javapoet.ClassName) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 19 with SQLiteEntity

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity 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)

Example 20 with SQLiteEntity

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity in project kripton by xcesco.

the class ModifyBeanHelper method generateWhereCondition.

/**
 * @param methodBuilder
 * @param method
 * @param analyzer
 */
public void generateWhereCondition(MethodSpec.Builder methodBuilder, SQLiteModelMethod method, SqlAnalyzer analyzer) {
    SQLiteDaoDefinition daoDefinition = method.getParent();
    SQLiteEntity entity = daoDefinition.getEntity();
    String beanParamName = method.getParameters().get(0).value0;
    SQLProperty property;
    boolean nullable;
    TypeName beanClass = typeName(entity.getElement());
    for (String item : analyzer.getUsedBeanPropertyNames()) {
        property = entity.findPropertyByName(item);
        // methodBuilder.addCode("_sqlWhereParams.add(");
        methodBuilder.addCode("_contentValues.addWhereArgs(");
        nullable = TypeUtility.isNullable(property);
        if (nullable && !(property.hasTypeAdapter())) {
            // transform null in ""
            methodBuilder.addCode("($L==null?\"\":", getter(beanParamName, beanClass, property));
        }
        // check for string conversion
        TypeUtility.beginStringConversion(methodBuilder, property);
        SQLTransformer.javaProperty2WhereCondition(methodBuilder, method, beanParamName, beanClass, property);
        // check for string conversion
        TypeUtility.endStringConversion(methodBuilder, property);
        if (nullable && !(property.hasTypeAdapter())) {
            methodBuilder.addCode(")");
        }
        methodBuilder.addCode(");\n");
    }
}
Also used : TypeName(com.squareup.javapoet.TypeName) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)

Aggregations

SQLiteEntity (com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)30 SQLiteDaoDefinition (com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)25 SQLProperty (com.abubusoft.kripton.processor.sqlite.model.SQLProperty)23 TypeName (com.squareup.javapoet.TypeName)19 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)7 Pair (com.abubusoft.kripton.common.Pair)6 InvalidMethodSignException (com.abubusoft.kripton.processor.exceptions.InvalidMethodSignException)6 JQLProjection (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLProjection)6 ArrayList (java.util.ArrayList)6 One (com.abubusoft.kripton.common.One)5 ModelAnnotation (com.abubusoft.kripton.processor.core.ModelAnnotation)5 ClassName (com.squareup.javapoet.ClassName)5 MethodSpec (com.squareup.javapoet.MethodSpec)5 SQLTypeAdapterUtils (com.abubusoft.kripton.common.SQLTypeAdapterUtils)4 ModelProperty (com.abubusoft.kripton.processor.core.ModelProperty)4 GeneratedTypeElement (com.abubusoft.kripton.processor.element.GeneratedTypeElement)4 PropertyNotFoundException (com.abubusoft.kripton.processor.exceptions.PropertyNotFoundException)4 JQLReplacerListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)4 ArrayTypeName (com.squareup.javapoet.ArrayTypeName)4 SQLiteStatement (android.database.sqlite.SQLiteStatement)3