Search in sources :

Example 36 with SQLiteDaoDefinition

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

the class SqlBuilderHelper method generateLog.

/**
 * <p>
 * Generate log for INSERT operations
 * </p>
 *
 * @param method
 * @param methodBuilder
 */
public static void generateLog(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
    SQLiteDaoDefinition daoDefinition = method.getParent();
    // log is enabled
    if (daoDefinition.isLogEnabled()) {
        // generate log section - BEGIN
        methodBuilder.addComment("log section BEGIN");
        methodBuilder.beginControlFlow("if (_context.isLogEnabled())");
        methodBuilder.addCode("// log for insert -- BEGIN \n");
        JQLChecker checker = JQLChecker.getInstance();
        final One<Boolean> inWhere = new One<Boolean>(false);
        String sql = checker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

            @Override
            public String onBindParameter(String bindParameterName) {
                if (inWhere.value0) {
                    return "?";
                }
                return null;
            }

            @Override
            public void onWhereStatementBegin(Where_stmtContext ctx) {
                super.onWhereStatementBegin(ctx);
                inWhere.value0 = true;
            }

            @Override
            public void onWhereStatementEnd(Where_stmtContext ctx) {
                super.onWhereStatementEnd(ctx);
                inWhere.value0 = false;
            }
        });
        if (method.jql.containsSelectOperation) {
            // log
            // manage log
            methodBuilder.addCode("\n");
            methodBuilder.addStatement("$T.info($S)", Logger.class, sql);
        } else {
            sql = checker.replaceVariableStatements(method, sql, new JQLReplaceVariableStatementListenerImpl() {

                @Override
                public String onColumnNameSet(String statement) {
                    return "%s";
                }

                @Override
                public String onColumnValueSet(String statement) {
                    return "%s";
                }
            });
            methodBuilder.addStatement("$T _columnNameBuffer=new $T()", StringBuffer.class, StringBuffer.class);
            methodBuilder.addStatement("$T _columnValueBuffer=new $T()", StringBuffer.class, StringBuffer.class);
            methodBuilder.addStatement("String _columnSeparator=$S", "");
            SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.keys()", false, new OnColumnListener() {

                @Override
                public void onColumnCheck(MethodSpec.Builder methodBuilder, String columNameVariable) {
                    methodBuilder.addStatement("_columnNameBuffer.append(_columnSeparator+$L)", columNameVariable);
                    methodBuilder.addStatement("_columnValueBuffer.append(_columnSeparator+$S+$L)", ":", columNameVariable);
                    methodBuilder.addStatement("_columnSeparator=$S", ", ");
                }
            });
            methodBuilder.addStatement("$T.info($S, _columnNameBuffer.toString(), _columnValueBuffer.toString())", Logger.class, sql);
        }
        generateLogForContentValues(method, methodBuilder);
        methodBuilder.addCode("// log for insert -- END \n\n");
        SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);
        // generate log section - END
        methodBuilder.endControlFlow();
        methodBuilder.addComment("log section END");
    }
}
Also used : JQLReplaceVariableStatementListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplaceVariableStatementListenerImpl) Where_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext) JQLChecker(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker) MethodSpec(com.squareup.javapoet.MethodSpec) One(com.abubusoft.kripton.common.One) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)

Example 37 with SQLiteDaoDefinition

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

the class SqlModifyBuilder method generateModifierForContentProvider.

/**
 * <p>
 * Generate update and delete used in content provider class.
 * </p>
 *
 * @param elementUtils
 * @param builder
 * @param method
 * @param updateResultType
 */
private static void generateModifierForContentProvider(Elements elementUtils, Builder builder, final SQLiteModelMethod method, ModifyType updateResultType) {
    final SQLiteDaoDefinition daoDefinition = method.getParent();
    final SQLiteEntity entity = daoDefinition.getEntity();
    final Set<String> columns = new LinkedHashSet<>();
    JQLChecker jqlChecker = JQLChecker.getInstance();
    // parameters extracted from query
    final One<String> whereStatement = new One<>();
    if (method.jql.isWhereConditions()) {
        // parameters extracted from query
        final One<Boolean> alreadyFoundWhereStatement = new One<>(false);
        // put in whereStatement value of where statement.
        jqlChecker.replaceVariableStatements(method, method.jql.value, new JQLReplaceVariableStatementListenerImpl() {

            @Override
            public String onWhere(String statement) {
                if (alreadyFoundWhereStatement.value0 == false) {
                    whereStatement.value0 = statement;
                    alreadyFoundWhereStatement.value0 = true;
                    return "";
                } else {
                    // DO NOTHING
                    return null;
                }
            }
        });
    }
    List<JQLPlaceHolder> placeHolders = jqlChecker.extractFromVariableStatement(method, whereStatement.value0);
    // remove placeholder for dynamic where, we are not interested here
    placeHolders = SqlBuilderHelper.removeDynamicPlaceHolder(placeHolders);
    checkContentProviderVarsAndArguments(method, placeHolders);
    // detect column used for content value
    jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

        @Override
        public String onColumnNameToUpdate(String columnName) {
            SQLProperty tempProperty = entity.get(columnName);
            AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
            columns.add(tempProperty.columnName);
            return null;
        }
    });
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.contentProviderMethodName);
    // params
    methodBuilder.addParameter(ParameterSpec.builder(Uri.class, "uri").build());
    if (updateResultType == ModifyType.UPDATE_BEAN || updateResultType == ModifyType.UPDATE_RAW) {
        methodBuilder.addParameter(ParameterSpec.builder(ContentValues.class, "contentValues").build());
    }
    methodBuilder.addParameter(ParameterSpec.builder(String.class, "selection").build());
    methodBuilder.addParameter(ParameterSpec.builder(ArrayTypeName.of(String.class), "selectionArgs").build());
    methodBuilder.returns(Integer.TYPE);
    // retrieve content values
    if (updateResultType == ModifyType.UPDATE_BEAN || updateResultType == ModifyType.UPDATE_RAW) {
        methodBuilder.addStatement("$T _contentValues=contentValuesForContentProvider(contentValues)", KriptonContentValues.class);
    } else {
        methodBuilder.addStatement("$T _contentValues=contentValues()", KriptonContentValues.class);
    }
    SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);
    // query builder
    methodBuilder.addStatement("$T _sqlBuilder=sqlBuilder()", StringBuilder.class);
    generateInitForDynamicWhereVariables(method, methodBuilder, "selection", "selectionArgs");
    SqlBuilderHelper.generateWhereCondition(methodBuilder, method, false);
    int i = 0;
    // every controls was done in constructor of SQLiteModelMethod
    for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
        AssertKripton.assertTrue(SqlBuilderHelper.validate(variable.value, placeHolders, i), "In '%s.%s' content provider URI path variables and variables in where conditions are different. If SQL uses parameters, they must be defined in URI path.", daoDefinition.getName(), method.getName());
        JQLParameterName paramName = JQLParameterName.parse(variable.value);
        SQLProperty entityProperty = entity.get(paramName.getValue());
        if (entityProperty != null) {
            methodBuilder.addCode("// Add parameter $L at path segment $L\n", variable.value, variable.pathSegmentIndex);
            // methodBuilder.addStatement("_sqlWhereParams.add(uri.getPathSegments().get($L))",
            // variable.pathSegmentIndex);
            methodBuilder.addStatement("_contentValues.addWhereArgs(uri.getPathSegments().get($L))", variable.pathSegmentIndex);
            AssertKripton.assertTrue(TypeUtility.isTypeIncludedIn(entityProperty.getPropertyType().getTypeName(), String.class, Long.class, Long.TYPE), "In '%s.%s' content provider URI path variables %s must be String of Long type", daoDefinition.getName(), method.getName(), entityProperty.getName());
        }
        i++;
    }
    if (method.hasDynamicWhereConditions() && method.hasDynamicWhereArgs()) {
        // ASSERT: only with dynamic where conditions
        methodBuilder.beginControlFlow("if ($T.hasText(_sqlDynamicWhere) && _sqlDynamicWhereArgs!=null)", StringUtils.class);
        if (method.hasDynamicWhereConditions()) {
            methodBuilder.beginControlFlow("for (String _arg: _sqlDynamicWhereArgs)");
            // methodBuilder.addStatement("_sqlWhereParams.add(_arg)");
            methodBuilder.addStatement("_contentValues.addWhereArgs(_arg)");
            methodBuilder.endControlFlow();
        }
        methodBuilder.endControlFlow();
    }
    // column checj
    switch(updateResultType) {
        case UPDATE_BEAN:
        case UPDATE_RAW:
            SqlBuilderHelper.generateColumnCheckSet(builder, method, columns);
            SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.values().keySet()", true, null);
            break;
        default:
            break;
    }
    // generate log section - BEGIN
    methodBuilder.addComment("log section BEGIN");
    methodBuilder.beginControlFlow("if (_context.isLogEnabled())");
    generateLogForModifiers(method, methodBuilder);
    if (method.jql.operationType == JQLType.UPDATE) {
        // generate log for content values
        SqlBuilderHelper.generateLogForContentValues(method, methodBuilder);
    }
    // log for where parames
    SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);
    // generate log section - END
    methodBuilder.endControlFlow();
    methodBuilder.addComment("log section END");
    methodBuilder.addCode("\n// execute SQL\n");
    switch(updateResultType) {
        case DELETE_BEAN:
        case DELETE_RAW:
            methodBuilder.addStatement("int result = database().delete($S, _sqlWhereStatement, _contentValues.whereArgsAsArray())", daoDefinition.getEntity().getTableName());
            if (method.getParent().getParent().generateRx) {
                GenericSQLHelper.generateSubjectNext(methodBuilder, SubjectType.DELETE);
            }
            break;
        case UPDATE_BEAN:
        case UPDATE_RAW:
            if (method.jql.conflictAlgorithmType == ConflictAlgorithmType.NONE) {
                methodBuilder.addStatement("int result = database().update($S, _contentValues.values(), _sqlWhereStatement, _contentValues.whereArgsAsArray())", daoDefinition.getEntity().getTableName());
            } else {
                methodBuilder.addCode("// conflict algorithm $L\n", method.jql.conflictAlgorithmType);
                methodBuilder.addStatement("int result = database().updateWithOnConflict($S, _contentValues.values(), _sqlWhereStatement, _contentValues.whereArgsAsArray()), $L)", daoDefinition.getEntity().getTableName(), method.jql.conflictAlgorithmType.getConflictAlgorithm());
            }
            if (method.getParent().getParent().generateRx) {
                GenericSQLHelper.generateSubjectNext(methodBuilder, SubjectType.UPDATE);
            }
            break;
    }
    // support for livedata
    if (daoDefinition.hasLiveData()) {
        methodBuilder.addComment("support for livedata");
        methodBuilder.addStatement(BindDaoBuilder.METHOD_NAME_REGISTRY_EVENT + "(result)");
    }
    methodBuilder.addStatement("return result");
    // we add at last javadoc, because need info is built at last.
    SqlBuilderHelper.generateJavaDocForContentProvider(method, methodBuilder);
    methodBuilder.addJavadoc("@param uri $S\n", method.contentProviderUriTemplate.replace("*", "[*]"));
    switch(updateResultType) {
        case UPDATE_BEAN:
        case UPDATE_RAW:
            methodBuilder.addJavadoc("@param contentValues content values\n");
            break;
        default:
            break;
    }
    methodBuilder.addJavadoc("@param selection dynamic part of <code>where</code> statement $L\n", method.hasDynamicWhereConditions() ? "" : "<b>NOT USED</b>");
    methodBuilder.addJavadoc("@param selectionArgs arguments of dynamic part of <code>where</code> statement $L\n", method.hasDynamicWhereConditions() ? "" : "<b>NOT USED</b>");
    methodBuilder.addJavadoc("@return number of effected rows\n");
    builder.addMethod(methodBuilder.build());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) JQLReplaceVariableStatementListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplaceVariableStatementListenerImpl) JQLChecker(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker) JQLParameterName(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker.JQLParameterName) MethodSpec(com.squareup.javapoet.MethodSpec) One(com.abubusoft.kripton.common.One) JQLPlaceHolder(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLPlaceHolder) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) ContentUriPlaceHolder(com.abubusoft.kripton.processor.sqlite.grammars.uri.ContentUriPlaceHolder) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)

Example 38 with SQLiteDaoDefinition

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

the class GenericSQLHelper method generateGenericExecSQL.

/**
 * @param methodBuilder
 * @param method
 * @param daoDefinition
 * @param schema
 */
public static void generateGenericExecSQL(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method) {
    final SQLiteDaoDefinition daoDefinition = method.getParent();
    boolean nullable;
    final List<String> paramsList = new ArrayList<String>();
    final List<String> contentValueList = new ArrayList<String>();
    final One<Boolean> columnsToUpdate = new One<Boolean>(true);
    String sql = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

        @Override
        public void onWhereStatementBegin(Where_stmtContext ctx) {
            super.onWhereStatementBegin(ctx);
            columnsToUpdate.value0 = false;
        }

        @Override
        public void onWhereStatementEnd(Where_stmtContext ctx) {
            super.onWhereStatementEnd(ctx);
            columnsToUpdate.value0 = true;
        }

        @Override
        public String onColumnName(String columnName) {
            String resolvedName = currentSchema.findColumnNameByPropertyName(method, columnName);
            AssertKripton.assertTrueOrUnknownPropertyInJQLException(resolvedName != null, method, columnName);
            return resolvedName;
        }

        @Override
        public String onBindParameter(String bindParameterName) {
            String propertyName = method.findParameterAliasByName(bindParameterName);
            if (columnsToUpdate.value0) {
                contentValueList.add(propertyName);
            } else {
                paramsList.add(propertyName);
            }
            return "?";
        }
    });
    // update/insert columns
    final SQLiteEntity entity = daoDefinition.getEntity();
    for (String item : contentValueList) {
        // ASSERT: property is always in entity
        String propertyName = method.findParameterNameByAlias(item);
        TypeName paramType = method.findParameterTypeByAliasOrName(item);
        SQLProperty property = entity.get(item);
        if (propertyName == null)
            throw (new PropertyNotFoundException(method, propertyName, paramType));
        Pair<String, TypeName> methodParam = new Pair<String, TypeName>(propertyName, paramType);
        // check same type
        TypeUtility.checkTypeCompatibility(method, methodParam, property);
        if (method.isLogEnabled()) {
            methodBuilder.addCode("_contentValues.put($S, ", property.columnName);
        } else {
            methodBuilder.addCode("_contentValues.put(");
        }
        // it does not need to be converted in string
        SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, methodParam.value0, methodParam.value1, 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();
    // }
    }
    // where condition
    methodBuilder.addComment("build where condition");
    {
        // String separator = "";
        TypeName paramType;
        String realName;
        for (String item : paramsList) {
            methodBuilder.addCode("_contentValues.addWhereArgs(");
            paramType = method.findParameterTypeByAliasOrName(item);
            realName = method.findParameterNameByAlias(item);
            AssertKripton.assertTrueOrUnknownPropertyInJQLException(paramType != null, method, item);
            // code for query arguments
            nullable = TypeUtility.isNullable(paramType);
            if (nullable) {
                methodBuilder.addCode("($L==null?\"\":", realName);
            }
            // check for string conversion
            TypeUtility.beginStringConversion(methodBuilder, paramType);
            SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, realName, paramType, null);
            // check for string conversion
            TypeUtility.endStringConversion(methodBuilder, paramType);
            if (nullable) {
                methodBuilder.addCode(")");
            }
            methodBuilder.addCode(");\n");
        }
    }
    // log for where parames
    SqlBuilderHelper.generateLog(method, methodBuilder);
    // log
    methodBuilder.addCode("\n");
    methodBuilder.addStatement("database().execSQL($S, _contentValues.whereArgsAsArray())", sql);
}
Also used : Where_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext) TypeName(com.squareup.javapoet.TypeName) PropertyNotFoundException(com.abubusoft.kripton.processor.exceptions.PropertyNotFoundException) One(com.abubusoft.kripton.common.One) ArrayList(java.util.ArrayList) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) Pair(com.abubusoft.kripton.common.Pair)

Example 39 with SQLiteDaoDefinition

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

the class InsertRawHelper method generateJavaDoc.

/**
 * @param methodBuilder
 * @param method
 * @param returnType
 * @return string sql
 */
public String generateJavaDoc(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, TypeName returnType) {
    final SQLiteDaoDefinition daoDefinition = method.getParent();
    final SQLiteEntity entity = daoDefinition.getEntity();
    final One<Boolean> inColumnValues = new One<Boolean>(false);
    final List<Pair<String, TypeName>> methodParamsUsedAsColumnValue = new ArrayList<>();
    final List<Pair<String, TypeName>> methodParamsUsedAsParameter = new ArrayList<>();
    // transform JQL to SQL
    String sqlInsert = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

        @Override
        public void onColumnValueSetBegin(Column_value_setContext ctx) {
            inColumnValues.value0 = true;
        }

        @Override
        public void onColumnValueSetEnd(Column_value_setContext ctx) {
            inColumnValues.value0 = false;
        }

        @Override
        public String onColumnName(String columnName) {
            Set<SQLProperty> property = currentSchema.getPropertyBySimpleName(columnName);
            AssertKripton.assertTrueOrUnknownPropertyInJQLException(property != null, method, columnName);
            SQLProperty tempProperty = property.iterator().next();
            AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
            return tempProperty.columnName;
        }

        @Override
        public String onBindParameter(String bindParameterName) {
            String resolvedParamName = method.findParameterNameByAlias(bindParameterName);
            if (inColumnValues.value0) {
                methodParamsUsedAsColumnValue.add(new Pair<>(resolvedParamName, method.findParameterType(resolvedParamName)));
            } else {
                methodParamsUsedAsParameter.add(new Pair<>(resolvedParamName, method.findParameterType(resolvedParamName)));
            }
            return "${" + resolvedParamName + "}";
        }
    });
    methodBuilder.addJavadoc("<h2>SQL insert</h2>\n");
    methodBuilder.addJavadoc("<pre>$L</pre>\n", sqlInsert);
    methodBuilder.addJavadoc("\n");
    if (methodParamsUsedAsColumnValue.size() > 0) {
        // list of inserted fields
        methodBuilder.addJavadoc("<h2>Inserted columns:</strong></h2>\n");
        methodBuilder.addJavadoc("<dl>\n");
        for (Pair<String, TypeName> property : methodParamsUsedAsColumnValue) {
            // String resolvedName = method.findParameterAliasByName(property.value0);
            String resolvedName = method.findParameterNameByAlias(property.value0);
            /*SQLProperty prop = entity.get(resolvedName);
								
				if (prop == null)
					throw (new PropertyNotFoundException(method, property.value0, property.value1));*/
            methodBuilder.addJavadoc("\t<dt>$L</dt>", property.value0);
            methodBuilder.addJavadoc("<dd>is binded to query's parameter <strong>$L</strong> and method's parameter <strong>$L</strong></dd>\n", "${" + property.value0 + "}", resolvedName);
        }
        methodBuilder.addJavadoc("</dl>\n\n");
    }
    // list of parameters
    if (methodParamsUsedAsParameter.size() > 0) {
        methodBuilder.addJavadoc("<h2>Method parameters used as sql parameters</h2>\n");
        methodBuilder.addJavadoc("<dl>\n");
        for (Pair<String, TypeName> property : methodParamsUsedAsParameter) {
            String resolvedName = method.findParameterNameByAlias(property.value0);
            methodBuilder.addJavadoc("\t<dt>$L</dt>", resolvedName);
            methodBuilder.addJavadoc("<dd>is binded to query's parameter <strong>$${$L}</strong></dd>\n", property.value0);
        }
        methodBuilder.addJavadoc("</dl>\n\n");
    }
    for (Pair<String, TypeName> param : method.getParameters()) {
        if (methodParamsUsedAsColumnValue.contains(param)) {
            methodBuilder.addJavadoc("@param $L\n", param.value0);
            if (entity.get(method.findParameterAliasByName(param.value0)) != null) {
                methodBuilder.addJavadoc("\tis binded to column value <strong>$L</strong>\n", entity.get(method.findParameterAliasByName(param.value0)).columnName);
            } else {
                // in case of JQL explicit, you can declare name of parameter
                methodBuilder.addJavadoc("\tis binded to query parameter <strong>$L</strong>\n", param.value0);
            }
        }
        if (methodParamsUsedAsParameter.contains(param)) {
            methodBuilder.addJavadoc("@param $L\n", param.value0);
            methodBuilder.addJavadoc("\tis used as parameter\n");
        }
    }
    generateJavaDocReturnType(methodBuilder, returnType);
    return sqlInsert;
}
Also used : TypeName(com.squareup.javapoet.TypeName) Set(java.util.Set) One(com.abubusoft.kripton.common.One) ArrayList(java.util.ArrayList) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) Column_value_setContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_value_setContext) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) Pair(com.abubusoft.kripton.common.Pair)

Example 40 with SQLiteDaoDefinition

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

the class InsertRawHelper method generate.

@Override
public void generate(TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, boolean mapFields, final SQLiteModelMethod method, TypeName returnType) {
    final SQLiteDaoDefinition daoDefinition = method.getParent();
    final SQLiteEntity entity = daoDefinition.getEntity();
    // boolean nullable;
    // generate javadoc
    generateJavaDoc(methodBuilder, method, returnType);
    // standard INSERT
    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) {
        // INSERT-SELECT
        GenericSQLHelper.generateGenericExecSQL(methodBuilder, method);
    } else {
        methodBuilder.addCode("\n");
        List<Pair<String, TypeName>> fieldsToUpdate = method.getParameters();
        fieldsToUpdate = SqlBuilderHelper.orderContentValues(method, fieldsToUpdate);
        for (Pair<String, TypeName> item : fieldsToUpdate) {
            String propertyName = method.findParameterAliasByName(item.value0);
            SQLProperty property = entity.get(propertyName);
            if (property == null)
                throw (new PropertyNotFoundException(method, propertyName, item.value1));
            // check same type
            TypeUtility.checkTypeCompatibility(method, item, property);
            if (method.isLogEnabled()) {
                methodBuilder.addCode("_contentValues.put($S, ", property.columnName);
            } else {
                methodBuilder.addCode("_contentValues.put(");
            }
            // it does not need to be converted in string
            SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, item.value0, item.value1, property);
            methodBuilder.addCode(");\n");
        }
        methodBuilder.addCode("\n");
        SqlBuilderHelper.generateLog(method, methodBuilder);
        methodBuilder.addComment("insert operation");
        if (method.jql.hasDynamicParts() || method.jql.containsSelectOperation) {
            // does not memorize compiled statement, it can vary every time generate SQL for insert
            SqlBuilderHelper.generateSQLForInsertDynamic(method, methodBuilder);
            methodBuilder.addStatement("long result = $T.insert(_context, _sql, _contentValues)", KriptonDatabaseWrapper.class);
        } else {
            String psName = method.buildPreparedStatementName();
            methodBuilder.addStatement("long result = $T.insert($L, _contentValues)", KriptonDatabaseWrapper.class, psName);
        }
        if (daoDefinition.getParent().generateRx) {
            GenericSQLHelper.generateSubjectNext(methodBuilder, SubjectType.INSERT);
        }
        // support for livedata
        if (daoDefinition.hasLiveData()) {
            methodBuilder.addComment("support for livedata");
            methodBuilder.addStatement(BindDaoBuilder.METHOD_NAME_REGISTRY_EVENT + "(result)");
        }
        // define return value
        if (returnType == TypeName.VOID) {
        } else if (TypeUtility.isTypeIncludedIn(returnType, Boolean.TYPE, Boolean.class)) {
            methodBuilder.addCode("return result!=-1;\n");
        } else if (TypeUtility.isTypeIncludedIn(returnType, Long.TYPE, Long.class)) {
            methodBuilder.addCode("return result;\n");
        } else if (TypeUtility.isTypeIncludedIn(returnType, Integer.TYPE, Integer.class)) {
            methodBuilder.addCode("return (int)result;\n");
        } 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) 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) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) Pair(com.abubusoft.kripton.common.Pair)

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