Search in sources :

Example 1 with JQLDynamicStatementType

use of com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType in project kripton by xcesco.

the class SqlBuilderHelper method generateWhereCondition.

/**
 * <p>
 * Generate where management code.
 * </p>
 *
 * <h2>pre condition</h2>
 * <dl>
 * <dt>_sqlDynamicWhere</dt>
 * <dd>dynamic where</dd>
 * </dl>
 *
 * <h2>post conditions</h2>
 * <dl>
 * <dt>_sqlWhereParams</dt>
 * <dd>ArraList</dd>
 * <dt>_sqlWhereStatement</dt>
 * <dd>String</dd>
 * </dl>
 *
 * @param methodBuilder
 * @param method
 * @param jql
 * @param jqlChecker
 * @param sqlWhereStatement
 */
public static void generateWhereCondition(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, boolean sqlWhereParamsAlreadyDefined) {
    final JQL jql = method.jql;
    final JQLChecker jqlChecker = JQLChecker.getInstance();
    // we need always this
    if (!sqlWhereParamsAlreadyDefined) {
    // methodBuilder.addStatement("$T<String>
    // _sqlWhereParams=getWhereParamsArray()", ArrayList.class);
    }
    if (jql.isWhereConditions()) {
        // parameters extracted from query
        final One<String> whereStatement = new One<>();
        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;
                }
            }
        });
        methodBuilder.addCode("\n// manage WHERE arguments -- BEGIN\n");
        String sqlWhere = jqlChecker.replaceFromVariableStatement(method, whereStatement.value0, new JQLReplacerListenerImpl(method) {

            @Override
            public String onColumnName(String columnName) {
                SQLProperty tempProperty = currentEntity.get(columnName);
                AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
                return tempProperty.columnName;
            }

            @Override
            public String onDynamicSQL(JQLDynamicStatementType dynamicStatement) {
                return null;
            }

            @Override
            public String onBindParameter(String bindParameterName) {
                return "?";
            }
        });
        methodBuilder.addCode("\n// manage WHERE statement\n");
        String value = sqlWhere;
        String valueToReplace = jql.dynamicReplace.get(JQLDynamicStatementType.DYNAMIC_WHERE);
        if (method.jql.operationType == JQLType.SELECT) {
            // we have to include WHERE keywords
            if (jql.isStaticWhereConditions() && !jql.isDynamicWhereConditions()) {
                // case static statement and NO dynamic
                methodBuilder.addStatement("String _sqlWhereStatement=$S", value);
            } else if (jql.isStaticWhereConditions() && jql.isDynamicWhereConditions()) {
                methodBuilder.addStatement("String _sqlWhereStatement=$S+$T.ifNotEmptyAppend($L,\" $L \")", value.replace(valueToReplace, ""), StringUtils.class, "_sqlDynamicWhere", method.dynamicWherePrepend);
            } else if (!jql.isStaticWhereConditions() && jql.isDynamicWhereConditions()) {
                methodBuilder.addStatement("String _sqlWhereStatement=$T.ifNotEmptyAppend($L, \" $L \")", StringUtils.class, "_sqlDynamicWhere", JQLKeywords.WHERE_KEYWORD);
            }
        } else {
            // we DON'T have to include WHERE keywords
            value = value.replace(" " + JQLKeywords.WHERE_KEYWORD, "");
            if (jql.isStaticWhereConditions() && !jql.isDynamicWhereConditions()) {
                // case static statement and NO dynamic
                methodBuilder.addStatement("String _sqlWhereStatement=$S", value);
            } else if (jql.isStaticWhereConditions() && jql.isDynamicWhereConditions()) {
                methodBuilder.addStatement("String _sqlWhereStatement=$S+$T.ifNotEmptyAppend($L,\" $L \")", value.replace(valueToReplace, ""), StringUtils.class, "_sqlDynamicWhere", method.dynamicWherePrepend);
            } else if (!jql.isStaticWhereConditions() && jql.isDynamicWhereConditions()) {
                methodBuilder.addStatement("String _sqlWhereStatement=$T.ifNotEmptyAppend($L, \" \")", StringUtils.class, "_sqlDynamicWhere");
            }
        }
        methodBuilder.addStatement("_sqlBuilder.append($L)", "_sqlWhereStatement");
        methodBuilder.addCode("\n// manage WHERE arguments -- END\n");
    } else {
        // in every situation we need it
        methodBuilder.addStatement("String _sqlWhereStatement=\"\"");
    }
    // manage where arguments
    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();
    }
}
Also used : JQLReplaceVariableStatementListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplaceVariableStatementListenerImpl) JQLChecker(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker) JQL(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL) One(com.abubusoft.kripton.common.One) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) JQLDynamicStatementType(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType) StringUtils(com.abubusoft.kripton.common.StringUtils) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty)

Example 2 with JQLDynamicStatementType

use of com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType in project kripton by xcesco.

the class JQLBuilder method buildJQL.

public static JQL buildJQL(SQLiteModelMethod method, String preparedJql) {
    final SQLiteDaoDefinition dao = method.getParent();
    Map<JQLDynamicStatementType, String> dynamicReplace = new HashMap<>();
    final JQL result = new JQL();
    // for each method's parameter
    forEachParameter(method, new OnMethodParameterListener() {

        @Override
        public void onMethodParameter(VariableElement item) {
            if (dao.getEntity().getElement().asType().equals(item.asType())) {
                result.paramBean = item.getSimpleName().toString();
            }
        }
    });
    // defined how jql is defined
    result.declarationType = JQLDeclarationType.JQL_COMPACT;
    if (StringUtils.hasText(preparedJql)) {
        result.declarationType = JQLDeclarationType.JQL_EXPLICIT;
    }
    if (method.hasAnnotation(BindSqlSelect.class)) {
        checkFieldsDefinitions(method, BindSqlSelect.class);
        return buildJQLSelect(method, result, dynamicReplace, preparedJql);
    } else if (method.hasAnnotation(BindSqlInsert.class)) {
        checkFieldsDefinitions(method, BindSqlInsert.class);
        return buildJQLInsert(method, result, preparedJql);
    } else if (method.hasAnnotation(BindSqlUpdate.class)) {
        checkFieldsDefinitions(method, BindSqlUpdate.class);
        return buildJQLUpdate(method, result, dynamicReplace, preparedJql);
    } else if (method.hasAnnotation(BindSqlDelete.class)) {
        return buildJQLDelete(method, result, dynamicReplace, preparedJql);
    }
    return null;
}
Also used : JQLDynamicStatementType(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType) HashMap(java.util.HashMap) BindSqlDelete(com.abubusoft.kripton.android.annotation.BindSqlDelete) VariableElement(javax.lang.model.element.VariableElement) BindSqlInsert(com.abubusoft.kripton.android.annotation.BindSqlInsert) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)

Example 3 with JQLDynamicStatementType

use of com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType in project kripton by xcesco.

the class TestJqlChecker method testOK.

/**
 * <p>
 * OK
 * </p>
 *
 * @throws Throwable
 */
@Test
public void testOK() throws Throwable {
    String sql = "SELECT id, action, number, countryCode, contactName, contactId FROM phone_number WHERE number = ${bean.number} and number like ${bean.number} || '%' and #{" + JQLDynamicStatementType.DYNAMIC_WHERE + "}";
    log(sql);
    JQL jql = new JQL();
    jql.value = sql;
    JQLChecker jsqChecker = JQLChecker.getInstance();
    jsqChecker.analyze(dummyContext, jql, new JqlBaseListener() {

        @Override
        public void enterBind_parameter(Bind_parameterContext ctx) {
            TestJqlChecker.this.log("xx parameter name %s", ctx.bind_parameter_name().getText());
        }

        @Override
        public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
            TestJqlChecker.this.log("xx dynamic %s", ctx.bind_parameter_name().getText());
        }

        @Override
        public void enterColumn_name(Column_nameContext ctx) {
            super.enterColumn_name(ctx);
            log("column " + ctx.getText());
        }
    });
    jsqChecker.extractPlaceHoldersAsList(new JQLContext() {

        @Override
        public String getContextDescription() {
            return "test context";
        }
    }, jql.value);
    log("replaced " + jsqChecker.replace(dummyContext, jql, new JQLReplacerListenerImpl(null) {

        @Override
        public String onDynamicSQL(JQLDynamicStatementType dynamicStatement) {
            return String.format("\"+%s+\"", dynamicStatement);
        }

        @Override
        public String onBindParameter(String bindParameterName) {
            return "?";
        }

        @Override
        public String onColumnFullyQualifiedName(String tableName, String columnName) {
            // TODO Auto-generated method stub
            return null;
        }
    }));
    log("aa");
}
Also used : JQLContext(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLContext) JQLChecker(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) JQLDynamicStatementType(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType) JQL(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL) Bind_dynamic_sqlContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Bind_dynamic_sqlContext) JqlBaseListener(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener) Column_nameContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_nameContext) Bind_parameterContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Bind_parameterContext) BaseProcessorTest(base.BaseProcessorTest) Test(org.junit.Test)

Example 4 with JQLDynamicStatementType

use of com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType in project kripton by xcesco.

the class TestJqlChecker method testUpdate01.

@Test
public void testUpdate01() {
    String sql = "UPDATE channel SET uid=${ bean.field1}, owner_uid=${bean.field2}, update_time=${bean.field3}, name=${field4} WHERE id=${bean.field1}";
    String sqlForLog = "UPDATE channel SET uid=?, owner_uid=?, update_time=?, name=? WHERE id=?";
    JQL jql = new JQL();
    jql.value = sql;
    JQLChecker checker = JQLChecker.getInstance();
    // verify sql
    checker.verify(dummyContext, jql);
    // check bind parameters
    {
        List<JQLPlaceHolder> aspected = new ArrayList<>();
        aspected.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, "bean.field1"));
        aspected.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, "bean.field2"));
        aspected.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, "bean.field3"));
        aspected.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, "field4"));
        aspected.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, "bean.field1"));
        List<JQLPlaceHolder> actual = checker.extractPlaceHoldersAsList(dummyContext, jql.value);
        checkCollectionExactly(actual, aspected);
    }
    // prepare for log
    String sqlLogResult = checker.replace(dummyContext, jql, new JQLReplacerListenerImpl(null) {

        @Override
        public String onDynamicSQL(JQLDynamicStatementType dynamicStatement) {
            return String.format("\"+%s+\"", dynamicStatement);
        }

        @Override
        public String onBindParameter(String bindParameterName) {
            return "?";
        }

        @Override
        public String onColumnFullyQualifiedName(String tableName, String columnName) {
            // TODO Auto-generated method stub
            return null;
        }
    });
    assertEquals("sql for log generation failed", sqlForLog, sqlLogResult);
}
Also used : JQLChecker(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) JQLDynamicStatementType(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType) JQL(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL) ArrayList(java.util.ArrayList) List(java.util.List) JQLPlaceHolder(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLPlaceHolder) BaseProcessorTest(base.BaseProcessorTest) Test(org.junit.Test)

Example 5 with JQLDynamicStatementType

use of com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType in project kripton by xcesco.

the class TestJqlChecker method testSelect01.

/**
 * extract projections from a select
 */
@Test
public void testSelect01() {
    // String sql="SELECT count(*) FROM channel WHERE
    // updateTime=${bean.updateTime}";
    String sql = "SELECT count(*) as alias1, field2, field3 as alias3, table1.field3 as alias3, table2.field4 as alias4 FROM channel WHERE updateTime=${ bean.field1 } and field=${ field2  } and #{" + JQLDynamicStatementType.DYNAMIC_WHERE + "}";
    String logSql = "SELECT count(*) as alias1, field2, field3 as alias3, table1.field3 as alias3, table2.field4 as alias4 FROM channel WHERE updateTime=? and field=? and \"+DYNAMIC_WHERE+\"";
    // String usedSql = "SELECT count(*) FROM channel WHERE
    // updateTime=${bean.updateTime}";
    JQL jql = new JQL();
    jql.value = sql;
    JQLChecker checker = JQLChecker.getInstance();
    // verify sql
    checker.verify(dummyContext, jql);
    Finder<SQLProperty> entityMock = new Finder<SQLProperty>() {

        @Override
        public String getSimpleName() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public List<SQLProperty> getCollection() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public SQLProperty findPropertyByName(String name) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public String getTableName() {
            // TODO Auto-generated method stub
            return null;
        }
    };
    // check projections
    Set<JQLProjection> projections = checker.extractProjections(dummyContext, jql.value, entityMock);
    {
        LinkedHashSet<JQLProjection> aspected = new LinkedHashSet<>();
        aspected.add(JQLProjection.ProjectionBuilder.create().type(ProjectionType.COMPLEX).expression("count(*)").alias("alias1").build());
        aspected.add(JQLProjection.ProjectionBuilder.create().type(ProjectionType.COLUMN).column("field2").build());
        aspected.add(JQLProjection.ProjectionBuilder.create().type(ProjectionType.COLUMN).column("field3").alias("alias3").build());
        aspected.add(JQLProjection.ProjectionBuilder.create().type(ProjectionType.COLUMN).table("table1").column("field3").alias("alias3").build());
        aspected.add(JQLProjection.ProjectionBuilder.create().type(ProjectionType.COLUMN).table("table2").column("field4").alias("alias4").build());
        checkCollectionExactly(projections, aspected);
    }
    // check bind parameters
    {
        List<JQLPlaceHolder> aspected = new ArrayList<>();
        aspected.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, "bean.field1"));
        aspected.add(new JQLPlaceHolder(JQLPlaceHolderType.PARAMETER, "field2"));
        aspected.add(new JQLPlaceHolder(JQLPlaceHolderType.DYNAMIC_SQL, JQLDynamicStatementType.DYNAMIC_WHERE.toString()));
        List<JQLPlaceHolder> actual = checker.extractPlaceHoldersAsList(dummyContext, jql.value);
        checkCollectionExactly(actual, aspected);
    }
    // prepare for log
    String sqlLogResult = checker.replace(dummyContext, jql, new JQLReplacerListenerImpl(null) {

        @Override
        public String onDynamicSQL(JQLDynamicStatementType dynamicStatement) {
            return String.format("\"+%s+\"", dynamicStatement);
        }

        @Override
        public String onBindParameter(String bindParameterName) {
            return "?";
        }

        @Override
        public String onColumnFullyQualifiedName(String tableName, String columnName) {
            return null;
        }
    });
    assertEquals("sql for log generation failed", logSql, sqlLogResult);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) JQLChecker(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker) JQL(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL) Finder(com.abubusoft.kripton.processor.core.Finder) JQLPlaceHolder(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLPlaceHolder) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) JQLDynamicStatementType(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType) JQLProjection(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLProjection) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ArrayList(java.util.ArrayList) List(java.util.List) BaseProcessorTest(base.BaseProcessorTest) Test(org.junit.Test)

Aggregations

JQLDynamicStatementType (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType)6 JQL (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL)5 JQLChecker (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker)5 JQLReplacerListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)5 BaseProcessorTest (base.BaseProcessorTest)4 Test (org.junit.Test)4 JQLPlaceHolder (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLPlaceHolder)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 One (com.abubusoft.kripton.common.One)2 JQLContext (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLContext)2 JQLReplaceVariableStatementListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplaceVariableStatementListenerImpl)2 SQLProperty (com.abubusoft.kripton.processor.sqlite.model.SQLProperty)2 BindSqlDelete (com.abubusoft.kripton.android.annotation.BindSqlDelete)1 BindSqlInsert (com.abubusoft.kripton.android.annotation.BindSqlInsert)1 StringUtils (com.abubusoft.kripton.common.StringUtils)1 Finder (com.abubusoft.kripton.processor.core.Finder)1 JQLProjection (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLProjection)1 JqlBaseListener (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener)1 Bind_dynamic_sqlContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Bind_dynamic_sqlContext)1