Search in sources :

Example 41 with SQLiteDaoDefinition

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

the class ModifyRawHelper method generate.

@Override
public void generate(TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, boolean updateMode, SQLiteModelMethod method, TypeName returnType) {
    SQLiteDaoDefinition daoDefinition = method.getParent();
    SQLiteEntity entity = daoDefinition.getEntity();
    // separate params used for update bean and params used in
    // whereCondition
    // analyze whereCondition
    String whereCondition = extractWhereConditions(updateMode, method);
    // this method is invoked to check if every parameter is binded to an method param
    SqlUtility.extractParametersFromString(method.jql.value, method, entity);
    Pair<String, List<Pair<String, TypeName>>> where = SqlUtility.extractParametersFromString(whereCondition, method, entity);
    // defines which parameter is used like update field and which is used
    // in where condition.
    List<Pair<String, TypeName>> methodParams = method.getParameters();
    List<Pair<String, TypeName>> updateableParams = new ArrayList<Pair<String, TypeName>>();
    List<Pair<String, TypeName>> whereParams = new ArrayList<Pair<String, TypeName>>();
    String name;
    for (Pair<String, TypeName> param : methodParams) {
        name = method.findParameterAliasByName(param.value0);
        if (method.isThisDynamicWhereConditionsName(name)) {
            // skip for dynamic where
            continue;
        }
        if (method.isThisDynamicWhereArgsName(name)) {
            // skip for dynamic where
            continue;
        }
        if (where.value1.contains(new Pair<>(name, param.value1))) {
            whereParams.add(param);
        } else {
            updateableParams.add(param);
        }
    }
    // clear contentValues
    if (method.jql.hasDynamicParts() || method.jql.containsSelectOperation) {
        methodBuilder.addStatement("$T _contentValues=contentValuesForUpdate()", KriptonContentValues.class);
    } else {
        String psName = method.buildPreparedStatementName();
        // generate SQL for insert
        classBuilder.addField(FieldSpec.builder(TypeName.get(SQLiteStatement.class), psName, Modifier.PRIVATE, Modifier.STATIC).build());
        methodBuilder.beginControlFlow("if ($L==null)", psName);
        SqlBuilderHelper.generateSQLForStaticQuery(method, methodBuilder);
        methodBuilder.addStatement("$L = $T.compile(_context, _sql)", psName, KriptonDatabaseWrapper.class);
        methodBuilder.endControlFlow();
        methodBuilder.addStatement("$T _contentValues=contentValuesForUpdate($L)", KriptonContentValues.class, psName);
    }
    if (method.jql.containsSelectOperation) {
        generateJavaDoc(method, methodBuilder, updateMode);
        GenericSQLHelper.generateGenericExecSQL(methodBuilder, method);
    } else {
        // generate javadoc
        generateJavaDoc(method, methodBuilder, updateMode, whereCondition, where, methodParams);
        if (updateMode) {
            AssertKripton.assertTrueOrInvalidMethodSignException(updateableParams.size() > 0, method, "no column was selected for update");
            // order item for content values
            updateableParams = SqlBuilderHelper.orderContentValues(method, updateableParams);
            for (Pair<String, TypeName> item : updateableParams) {
                String resolvedParamName = method.findParameterAliasByName(item.value0);
                SQLProperty property = entity.get(resolvedParamName);
                if (property == null)
                    throw (new PropertyNotFoundException(method, resolvedParamName, item.value1));
                // check same type
                TypeUtility.checkTypeCompatibility(method, item, property);
                // here it needed raw parameter typeName
                if (method.isLogEnabled()) {
                    methodBuilder.addCode("_contentValues.put($S, ", property.columnName);
                } else {
                    methodBuilder.addCode("_contentValues.put(");
                }
                SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, item.value0, TypeUtility.typeName(property.getElement()), property);
                methodBuilder.addCode(");\n");
            // if (nullable) {
            // methodBuilder.nextControlFlow("else");
            // 
            // if (method.isLogEnabled()) {
            // methodBuilder.addStatement("_contentValues.putNull($S)", property.columnName);
            // } else {
            // methodBuilder.addStatement("_contentValues.putNull()");
            // }
            // 
            // methodBuilder.endControlFlow();
            // }
            }
            methodBuilder.addCode("\n");
        } else {
            if (updateableParams.size() > 0) {
                String separator = "";
                StringBuilder buffer = new StringBuilder();
                for (Pair<String, TypeName> item : updateableParams) {
                    String resolvedParamName = method.findParameterAliasByName(item.value0);
                    buffer.append(separator + resolvedParamName);
                    separator = ", ";
                }
                // in DELETE can not be updated fields
                if (updateableParams.size() > 1) {
                    throw (new InvalidMethodSignException(method, " parameters " + buffer.toString() + " are not used in where conditions"));
                } else {
                    throw (new InvalidMethodSignException(method, " parameter " + buffer.toString() + " is not used in where conditions"));
                }
            }
        }
        // build where condition
        generateWhereCondition(methodBuilder, method, where);
        methodBuilder.addCode("\n");
        ModifyBeanHelper.generateModifyQueryCommonPart(method, classBuilder, methodBuilder);
        // support for livedata
        if (daoDefinition.hasLiveData()) {
            methodBuilder.addComment("support for livedata");
            methodBuilder.addStatement(BindDaoBuilder.METHOD_NAME_REGISTRY_EVENT + "(result)");
        }
        // if true, field must be associate to ben attributes
        if (returnType == TypeName.VOID) {
        } else {
            if (isIn(returnType, Boolean.TYPE, Boolean.class)) {
                methodBuilder.addStatement("return result!=0");
            } else if (isIn(returnType, Long.TYPE, Long.class, Integer.TYPE, Integer.class, Short.TYPE, Short.class)) {
                methodBuilder.addStatement("return result");
            } else {
                // more than one listener found
                throw (new InvalidMethodSignException(method, "invalid return type"));
            }
        }
    }
}
Also used : TypeName(com.squareup.javapoet.TypeName) PropertyNotFoundException(com.abubusoft.kripton.processor.exceptions.PropertyNotFoundException) ArrayList(java.util.ArrayList) InvalidMethodSignException(com.abubusoft.kripton.processor.exceptions.InvalidMethodSignException) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) SQLiteStatement(android.database.sqlite.SQLiteStatement) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ArrayList(java.util.ArrayList) List(java.util.List) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) Pair(com.abubusoft.kripton.common.Pair)

Example 42 with SQLiteDaoDefinition

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

the class BindDaoFactoryBuilder method buildDaoFactoryInterfaceInternal.

/**
 * Build dao factory interface
 *
 * @param elementUtils
 * @param filer
 * @param schema
 *
 * @return schema typeName
 *
 * @throws Exception
 */
public TypeSpec.Builder buildDaoFactoryInterfaceInternal(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
    String schemaName = schema.getName();
    schemaName = PREFIX + schemaName;
    schemaName = schemaName.replace(BindDataSourceBuilder.SUFFIX, SUFFIX);
    classBuilder = TypeSpec.interfaceBuilder(schemaName).addModifiers(Modifier.PUBLIC).addSuperinterface(BindDaoFactory.class);
    classBuilder.addJavadoc("<p>\n");
    classBuilder.addJavadoc("Represents dao factory interface for $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", TypeUtility.typeName(schema.getElement()));
    for (SQLiteDaoDefinition dao : schema.getCollection()) {
        TypeName daoName = BindDaoBuilder.daoInterfaceTypeName(dao);
        TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);
        classBuilder.addJavadoc("@see $T\n", daoName);
        classBuilder.addJavadoc("@see $T\n", daoImplName);
        String entity = BindDataSourceSubProcessor.generateEntityName(dao, dao.getEntity());
        classBuilder.addJavadoc("@see $T\n", TypeUtility.typeName(entity));
    }
    for (SQLiteDaoDefinition dao : schema.getCollection()) {
        TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);
        // dao with external connections
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("get" + dao.getName()).addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).addJavadoc("\nretrieve dao $L\n", dao.getName()).returns(daoImplName);
            classBuilder.addMethod(methodBuilder.build());
        }
    }
    return classBuilder;
}
Also used : TypeName(com.squareup.javapoet.TypeName) BindDaoFactory(com.abubusoft.kripton.android.sqlite.BindDaoFactory) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)

Example 43 with SQLiteDaoDefinition

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

the class JQLBuilder method extractFieldsFromAnnotation.

/**
 * @param method
 * @param annotationClazz
 * @param includePrimaryKey
 * @param dao
 * @param entity
 * @return
 */
private static <A extends Annotation> LinkedHashSet<String> extractFieldsFromAnnotation(final SQLiteModelMethod method, Class<A> annotationClazz, final boolean includePrimaryKey) {
    final SQLiteDaoDefinition dao = method.getParent();
    final SQLiteEntity entity = method.getParent().getEntity();
    List<String> annotatedFieldValues = AnnotationUtility.extractAsStringArray(method.getElement(), annotationClazz, AnnotationAttributeType.FIELDS);
    List<String> annotatedExcludedFieldValues = AnnotationUtility.extractAsStringArray(method.getElement(), annotationClazz, AnnotationAttributeType.EXCLUDED_FIELDS);
    CollectionUtils.trim(annotatedFieldValues);
    CollectionUtils.trim(annotatedExcludedFieldValues);
    final One<Integer> count = new One<>(0);
    // extract properties from managed bean
    final Set<String> allFields = new LinkedHashSet<>();
    forEachFields(dao, new OnPropertyListener() {

        @Override
        public void onProperty(SQLProperty item) {
            if (!item.isPrimaryKey() || (item.isPrimaryKey() && includePrimaryKey)) {
                allFields.add(item.getName());
            }
            if (TypeUtility.isEquals(item.getPropertyType().getTypeName(), typeName(entity.getElement()))) {
                count.value0++;
            }
        }
    });
    // properties from selected set.
    if (annotatedFieldValues.size() == 0 && annotatedExcludedFieldValues.size() == 0) {
        // if no fields was selected, select all
        annotatedFieldValues.clear();
        annotatedFieldValues.addAll(allFields);
    } else if (annotatedExcludedFieldValues.size() > 0) {
        for (String fieldName : annotatedExcludedFieldValues) {
            if (!entity.contains(fieldName)) {
                AssertKripton.failUnknownPropertyInJQLException(method, annotationClazz, AnnotationAttributeType.EXCLUDED_FIELDS, fieldName);
            }
        }
        allFields.removeAll(annotatedExcludedFieldValues);
        annotatedFieldValues.clear();
        annotatedFieldValues.addAll(allFields);
    }
    LinkedHashSet<String> result = new LinkedHashSet<>();
    result.addAll(annotatedFieldValues);
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) One(com.abubusoft.kripton.common.One) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)

Aggregations

SQLiteDaoDefinition (com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)43 SQLiteEntity (com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)25 SQLProperty (com.abubusoft.kripton.processor.sqlite.model.SQLProperty)22 TypeName (com.squareup.javapoet.TypeName)21 Pair (com.abubusoft.kripton.common.Pair)9 JQLProjection (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLProjection)9 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)9 ArrayList (java.util.ArrayList)9 One (com.abubusoft.kripton.common.One)8 MethodSpec (com.squareup.javapoet.MethodSpec)8 InvalidMethodSignException (com.abubusoft.kripton.processor.exceptions.InvalidMethodSignException)6 ClassName (com.squareup.javapoet.ClassName)6 ModelAnnotation (com.abubusoft.kripton.processor.core.ModelAnnotation)5 JQLReplacerListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)5 ArrayTypeName (com.squareup.javapoet.ArrayTypeName)5 TypeSpec (com.squareup.javapoet.TypeSpec)5 SQLiteStatement (android.database.sqlite.SQLiteStatement)4 BindSqlUpdate (com.abubusoft.kripton.android.annotation.BindSqlUpdate)4 GeneratedTypeElement (com.abubusoft.kripton.processor.element.GeneratedTypeElement)4 JqlBaseListener (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener)4