Search in sources :

Example 6 with JQLReplacerListenerImpl

use of com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl 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 7 with JQLReplacerListenerImpl

use of com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl 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 8 with JQLReplacerListenerImpl

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

the class SqlInsertBuilder method generateInsertForContentProvider.

/**
 * <p>
 * Generate insert used in content provider class.
 * </p>
 *
 * @param methodBuilder
 * @param method
 * @param insertResultType
 */
private static void generateInsertForContentProvider(TypeSpec.Builder classBuilder, final SQLiteModelMethod method, InsertType insertResultType) {
    final SQLiteDaoDefinition daoDefinition = method.getParent();
    final SQLiteEntity entity = daoDefinition.getEntity();
    final Set<String> columns = new LinkedHashSet<>();
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.contentProviderMethodName);
    ParameterSpec parameterSpec;
    parameterSpec = ParameterSpec.builder(Uri.class, "uri").build();
    methodBuilder.addParameter(parameterSpec);
    parameterSpec = ParameterSpec.builder(ContentValues.class, "contentValues").build();
    methodBuilder.addParameter(parameterSpec);
    methodBuilder.returns(Long.TYPE);
    SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);
    // just detect which columns are admitted
    JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

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

        @Override
        public String onColumnFullyQualifiedName(String tableName, String columnName) {
            AssertKripton.fail("Inconsistent state");
            return null;
        }
    });
    // generate columnCheckSet
    SqlBuilderHelper.generateColumnCheckSet(classBuilder, method, columns);
    // retrieve content values
    methodBuilder.addStatement("$T _contentValues=contentValuesForContentProvider(contentValues)", KriptonContentValues.class);
    // generate column check
    SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.values().keySet()", true, null);
    methodBuilder.addCode("\n");
    // every controls was done in constructor of SQLiteModelMethod
    for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
        SQLProperty entityProperty = entity.get(variable.value);
        if (entityProperty != null) {
            methodBuilder.addCode("// Add parameter $L at path segment $L\n", variable.value, variable.pathSegmentIndex);
            TypeName entityPropertyType = entityProperty.getPropertyType().getTypeName();
            if (TypeUtility.isString(entityPropertyType)) {
                methodBuilder.addStatement("contentValues.put($S, uri.getPathSegments().get($L))", entityProperty.columnName, variable.pathSegmentIndex);
            } else {
                methodBuilder.addStatement("contentValues.put($S, Long.valueOf(uri.getPathSegments().get($L)))", entityProperty.columnName, variable.pathSegmentIndex);
            }
        }
    }
    // generate log for inser operation
    SqlBuilderHelper.generateLogForContentValuesContentProvider(method, methodBuilder);
    ConflictAlgorithmType conflictAlgorithmType = InsertBeanHelper.getConflictAlgorithmType(method);
    String conflictString1 = "";
    String conflictString2 = "";
    if (conflictAlgorithmType != ConflictAlgorithmType.NONE) {
        conflictString1 = "WithOnConflict";
        conflictString2 = ", " + conflictAlgorithmType.getConflictAlgorithm();
        methodBuilder.addCode("// conflict algorithm $L\n", method.jql.conflictAlgorithmType);
    }
    methodBuilder.addComment("insert operation");
    methodBuilder.addStatement("long result = database().insert$L($S, null, _contentValues.values()$L)", conflictString1, daoDefinition.getEntity().getTableName(), conflictString2);
    if (method.getParent().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>0?1:0)");
    }
    methodBuilder.addStatement("return result");
    // javadoc
    // 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("*", "[*]"));
    methodBuilder.addJavadoc("@param contentValues content values\n");
    methodBuilder.addJavadoc("@return new row's id\n");
    classBuilder.addMethod(methodBuilder.build());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) ParameterSpec(com.squareup.javapoet.ParameterSpec) ConflictAlgorithmType(com.abubusoft.kripton.android.sqlite.ConflictAlgorithmType) 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 9 with JQLReplacerListenerImpl

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

the class ModifyBeanHelper method extractSQLForJavaDoc.

private String extractSQLForJavaDoc(final SQLiteModelMethod method) {
    final One<Boolean> usedInWhere = new One<>(false);
    String sqlForJavaDoc = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

        @Override
        public String onColumnNameToUpdate(String columnName) {
            return currentEntity.findPropertyByName(columnName).columnName;
        }

        @Override
        public String onColumnName(String columnName) {
            return currentEntity.findPropertyByName(columnName).columnName;
        }

        @Override
        public String onBindParameter(String bindParameterName) {
            if (!usedInWhere.value0) {
                if (bindParameterName.contains(".")) {
                    String[] a = bindParameterName.split("\\.");
                    if (a.length == 2) {
                        bindParameterName = a[1];
                    }
                }
                return ":" + bindParameterName;
            } else {
                return null;
            }
        }

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

        @Override
        public void onWhereStatementEnd(Where_stmtContext ctx) {
            usedInWhere.value0 = false;
        }
    });
    return sqlForJavaDoc;
}
Also used : Where_stmtContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) One(com.abubusoft.kripton.common.One)

Example 10 with JQLReplacerListenerImpl

use of com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl 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

JQLReplacerListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)21 JQLChecker (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker)13 SQLProperty (com.abubusoft.kripton.processor.sqlite.model.SQLProperty)13 One (com.abubusoft.kripton.common.One)12 ArrayList (java.util.ArrayList)9 TypeName (com.squareup.javapoet.TypeName)7 Pair (com.abubusoft.kripton.common.Pair)6 SQLiteDaoDefinition (com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)6 JQL (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL)5 JQLDynamicStatementType (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQL.JQLDynamicStatementType)5 JQLReplaceVariableStatementListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplaceVariableStatementListenerImpl)5 Where_stmtContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext)5 SQLiteEntity (com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)5 BaseProcessorTest (base.BaseProcessorTest)4 JQLPlaceHolder (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLPlaceHolder)4 Test (org.junit.Test)4 JQLContext (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLContext)3 MethodSpec (com.squareup.javapoet.MethodSpec)3 LinkedHashSet (java.util.LinkedHashSet)3 List (java.util.List)3