Search in sources :

Example 1 with Column_value_setContext

use of com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_value_setContext in project kripton by xcesco.

the class JQLBuilder method buildJQLInsert.

/**
 * <pre>
 *
 * INSERT INTO person (name, surname, birth_city, birth_day) VALUES (${name}, ${surname}, ${birthCity}, ${birthDay})
 * </pre>
 *
 * @param method
 * @param preparedJql
 * @return
 */
private static JQL buildJQLInsert(SQLiteModelMethod method, final JQL result, String preparedJql) {
    if (StringUtils.hasText(preparedJql)) {
        result.value = preparedJql;
        // INSERT can contains bind parameter in column values and select
        // statement
        final One<Boolean> inColumnValueSet = new One<Boolean>(false);
        final One<Boolean> inWhereStatement = new One<Boolean>(false);
        JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {

            @Override
            public void enterConflict_algorithm(Conflict_algorithmContext ctx) {
                result.conflictAlgorithmType = ConflictAlgorithmType.valueOf(ctx.getText().toUpperCase());
            }

            @Override
            public void enterProjected_columns(Projected_columnsContext ctx) {
                result.containsSelectOperation = true;
            }

            @Override
            public void enterWhere_stmt(Where_stmtContext ctx) {
                inWhereStatement.value0 = true;
            }

            @Override
            public void exitWhere_stmt(Where_stmtContext ctx) {
                inWhereStatement.value0 = false;
            }

            @Override
            public void enterColumn_value_set(Column_value_setContext ctx) {
                inColumnValueSet.value0 = true;
            }

            @Override
            public void exitColumn_value_set(Column_value_setContext ctx) {
                inColumnValueSet.value0 = false;
            }

            @Override
            public void enterBind_parameter(Bind_parameterContext ctx) {
                if (inWhereStatement.value0) {
                    result.bindParameterOnWhereStatementCounter++;
                } else if (inColumnValueSet.value0) {
                    result.bindParameterAsColumnValueCounter++;
                }
                AssertKripton.assertTrue(inWhereStatement.value0 || inColumnValueSet.value0, "unknown situation!");
            }
        });
        if (result.containsSelectOperation) {
            AssertKripton.assertTrueOrInvalidMethodSignException(method.getReturnClass().equals(TypeName.VOID), method, "defined JQL requires that method's return type is void");
        }
    // ASSERT: a INSERT-SELECT SQL can not contains parameters on values
    // section.
    } else {
        // use annotation's attribute value and exclude and bean definition
        // to
        final Class<? extends Annotation> annotation = BindSqlInsert.class;
        final SQLiteDaoDefinition dao = method.getParent();
        final boolean includePrimaryKey = AnnotationUtility.extractAsBoolean(method.getElement(), annotation, AnnotationAttributeType.INCLUDE_PRIMARY_KEY);
        // define field list
        // every method parameter can be used only as insert field
        InsertType insertResultType = SqlInsertBuilder.detectInsertType(method);
        Set<String> fields;
        if (insertResultType == InsertType.INSERT_BEAN) {
            fields = extractFieldsFromAnnotation(method, annotation, includePrimaryKey);
        } else {
            fields = extractFieldsFromMethodParameters(method, annotation);
        }
        result.conflictAlgorithmType = ConflictAlgorithmType.valueOf(AnnotationUtility.extractAsEnumerationValue(method.getElement(), annotation, AnnotationAttributeType.CONFLICT_ALGORITHM_TYPE));
        StringBuilder builder = new StringBuilder();
        builder.append(INSERT_KEYWORD);
        builder.append(" " + result.conflictAlgorithmType.getSqlForInsert());
        builder.append(INTO_KEYWORD);
        builder.append(" " + dao.getEntitySimplyClassName());
        builder.append(" (");
        builder.append(forEachFields(fields, new OnFieldListener() {

            @Override
            public String onField(String item) {
                return item;
            }
        }));
        builder.append(") ");
        builder.append(VALUES_KEYWORD);
        final One<String> prefix = new One<>("");
        if (result.hasParamBean()) {
            prefix.value0 = result.paramBean + ".";
        }
        builder.append(" (");
        builder.append(forEachFields(fields, new OnFieldListener() {

            @Override
            public String onField(String item) {
                return "${" + prefix.value0 + item + "}";
            }
        }));
        builder.append(")");
        result.value = builder.toString();
    }
    result.operationType = JQLType.INSERT;
    result.dynamicReplace = new HashMap<>();
    return result;
}
Also used : Projected_columnsContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Projected_columnsContext) Where_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext) Conflict_algorithmContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Conflict_algorithmContext) One(com.abubusoft.kripton.common.One) JqlBaseListener(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener) Bind_parameterContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Bind_parameterContext) BindSqlInsert(com.abubusoft.kripton.android.annotation.BindSqlInsert) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) Column_value_setContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_value_setContext) InsertType(com.abubusoft.kripton.processor.sqlite.SqlInsertBuilder.InsertType)

Example 2 with Column_value_setContext

use of com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_value_setContext in project kripton by xcesco.

the class JQLChecker method replaceVariableStatements.

/**
 * <p>
 * Given a sql, replace som component like where, order by, etc..
 *
 * <p>
 * Note that only first level of variable statements will be replaced.
 *
 * @param jql
 * @param listener
 * @return
 */
public String replaceVariableStatements(final JQLContext jqlContext, final String jql, final JQLReplaceVariableStatementListener listener) {
    final List<Triple<Token, Token, String>> replace = new ArrayList<>();
    final One<Integer> currentSelectLevel = new One<Integer>(-1);
    JqlBaseListener rewriterListener = new JqlBaseListener() {

        @Override
        public void enterSelect_core(Select_coreContext ctx) {
            currentSelectLevel.value0++;
        }

        @Override
        public void enterSelect_or_values(Select_or_valuesContext ctx) {
            currentSelectLevel.value0++;
        }

        @Override
        public void exitSelect_core(Select_coreContext ctx) {
            currentSelectLevel.value0--;
        }

        @Override
        public void exitSelect_or_values(Select_or_valuesContext ctx) {
            currentSelectLevel.value0--;
        }

        @Override
        public void enterProjected_columns(Projected_columnsContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 1;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onProjectedColumns(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }

        @Override
        public void enterWhere_stmt(Where_stmtContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 1;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onWhere(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }

        @Override
        public void enterOrder_stmt(Order_stmtContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 1;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onOrderBy(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }

        @Override
        public void enterGroup_stmt(Group_stmtContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 1;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onGroup(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }

        @Override
        public void enterHaving_stmt(Having_stmtContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 1;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onHaving(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }

        @Override
        public void enterOffset_stmt(Offset_stmtContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 1;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onOffset(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }

        @Override
        public void enterLimit_stmt(Limit_stmtContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 1;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onLimit(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }

        @Override
        public void enterColumn_name_set(Column_name_setContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 2;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onColumnNameSet(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }

        @Override
        public void enterColumn_value_set(Column_value_setContext ctx) {
            // we work on level 0
            if (currentSelectLevel.value0 > 0)
                return;
            int start = ctx.getStart().getStartIndex() - 1;
            int stop = ctx.getStop().getStopIndex() + 2;
            if (start == stop)
                return;
            String statement = jql.substring(start, stop);
            String value = listener.onColumnValueSet(statement);
            if (value != null) {
                replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
            }
        }
    };
    return replaceInternal(jqlContext, jql, replace, rewriterListener);
}
Also used : Column_name_setContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_name_setContext) Projected_columnsContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Projected_columnsContext) Where_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext) Having_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Having_stmtContext) One(com.abubusoft.kripton.common.One) ArrayList(java.util.ArrayList) JqlBaseListener(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener) Group_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Group_stmtContext) Select_coreContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Select_coreContext) Token(org.antlr.v4.runtime.Token) Order_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Order_stmtContext) Select_or_valuesContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Select_or_valuesContext) Triple(com.abubusoft.kripton.common.Triple) Column_value_setContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_value_setContext) Limit_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Limit_stmtContext) Offset_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Offset_stmtContext)

Example 3 with Column_value_setContext

use of com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_value_setContext 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)

Aggregations

One (com.abubusoft.kripton.common.One)3 Column_value_setContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_value_setContext)3 JqlBaseListener (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener)2 Projected_columnsContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Projected_columnsContext)2 Where_stmtContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext)2 SQLiteDaoDefinition (com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)2 ArrayList (java.util.ArrayList)2 BindSqlInsert (com.abubusoft.kripton.android.annotation.BindSqlInsert)1 Pair (com.abubusoft.kripton.common.Pair)1 Triple (com.abubusoft.kripton.common.Triple)1 InsertType (com.abubusoft.kripton.processor.sqlite.SqlInsertBuilder.InsertType)1 JQLReplacerListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)1 Bind_parameterContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Bind_parameterContext)1 Column_name_setContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_name_setContext)1 Conflict_algorithmContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Conflict_algorithmContext)1 Group_stmtContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Group_stmtContext)1 Having_stmtContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Having_stmtContext)1 Limit_stmtContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Limit_stmtContext)1 Offset_stmtContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Offset_stmtContext)1 Order_stmtContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Order_stmtContext)1