Search in sources :

Example 16 with One

use of com.abubusoft.kripton.common.One in project kripton by xcesco.

the class TestSpeedRuntime method testSingle.

@Test
public void testSingle() {
    final One<Long> start = new One<>();
    final One<Long> end = new One<>();
    final int COUNTER = 200000;
    final BindPersonDataSource ds = BindPersonDataSource.instance();
    ds.execute(new Transaction() {

        @Override
        public TransactionResult onExecute(BindPersonDaoFactory daoFactory) {
            start.value0 = System.currentTimeMillis();
            PersonDaoImpl dao = daoFactory.getPersonDao();
            for (int i = 0; i < COUNTER; i++) {
                Person bean = new Person();
                bean.name = "name" + i;
                bean.surname = "surname" + i;
                // Object bean = new
                dao.insert(bean);
            }
            end.value0 = System.currentTimeMillis();
            return TransactionResult.COMMIT;
        }
    });
    // 3100
    System.out.println("Esecuzione terminata in " + (end.value0 - start.value0) + " ms");
}
Also used : TransactionResult(com.abubusoft.kripton.android.sqlite.TransactionResult) Transaction(sqlite.feature.speed.persistence.BindPersonDataSource.Transaction) One(com.abubusoft.kripton.common.One) BindPersonDataSource(sqlite.feature.speed.persistence.BindPersonDataSource) BindPersonDaoFactory(sqlite.feature.speed.persistence.BindPersonDaoFactory) PersonDaoImpl(sqlite.feature.speed.persistence.PersonDaoImpl) Person(sqlite.feature.speed.model.Person) Test(org.junit.Test) BaseAndroidTest(base.BaseAndroidTest)

Example 17 with One

use of com.abubusoft.kripton.common.One in project kripton by xcesco.

the class TestJqlChecker method testBindParametersFromVariableStatements.

@Test
public void testBindParametersFromVariableStatements() {
    final One<String> where = new One<>();
    final One<String> orderBy = new One<>();
    final One<String> limit = new One<>();
    final One<String> offset = new One<>();
    final One<String> group = new One<>();
    final One<String> having = new One<>();
    String sql = "SELECT id, parentId, birthCity, birthDay, value, name, surname FROM Person WHERE name like ${nameTemp} || '%' GROUP BY id HAVING id=2 ORDER BY id,  #{" + JQLDynamicStatementType.DYNAMIC_ORDER_BY + "} LIMIT #{" + JQLDynamicStatementType.DYNAMIC_PAGE_SIZE + "} OFFSET #{" + JQLDynamicStatementType.DYNAMIC_PAGE_OFFSET + "}";
    JQL jql = new JQL();
    jql.value = sql;
    JQLChecker checker = JQLChecker.getInstance();
    // verify sql
    checker.verify(dummyContext, jql);
    String finalSql = checker.replaceVariableStatements(dummyContext, jql.value, new JQLReplaceVariableStatementListenerImpl() {

        @Override
        public String onWhere(String whereStatement) {
            where.value0 = whereStatement;
            return "";
        }

        @Override
        public String onOrderBy(String orderByStatement) {
            orderBy.value0 = orderByStatement;
            return "";
        }

        @Override
        public String onLimit(String statement) {
            limit.value0 = statement;
            return "";
        }

        @Override
        public String onOffset(String statement) {
            offset.value0 = statement;
            return "";
        }

        @Override
        public String onGroup(String statement) {
            group.value0 = statement;
            return "";
        }

        @Override
        public String onHaving(String statement) {
            having.value0 = statement;
            return "";
        }

        @Override
        public String onProjectedColumns(String statement) {
            return null;
        }
    });
    log(where.value0);
    log(orderBy.value0);
    log(group.value0);
    log(having.value0);
    log(offset.value0);
    log(limit.value0);
    log(finalSql);
    // assertEquals(where, " id = ${dummy} and a=${dummy2}");
    {
        List<JQLPlaceHolder> list = checker.extractFromVariableStatement(new JQLContext() {

            @Override
            public String getContextDescription() {
                return "Test context";
            }
        }, where.value0);
        for (JQLPlaceHolder item : list) {
            log(item.value);
        }
        String replacedSql = checker.replaceFromVariableStatement(new JQLContext() {

            @Override
            public String getContextDescription() {
                return "Test context";
            }
        }, where.value0, new JQLReplacerListenerImpl(null) {

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

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

            @Override
            public String onColumnFullyQualifiedName(String tableName, String columnName) {
                // TODO Auto-generated method stub
                return null;
            }
        });
        log(replacedSql);
    }
}
Also used : JQLReplaceVariableStatementListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplaceVariableStatementListenerImpl) 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) One(com.abubusoft.kripton.common.One) 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 18 with One

use of com.abubusoft.kripton.common.One in project kripton by xcesco.

the class AbstractSelectCodeGenerator method generateCommonPart.

public void generateCommonPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields, GenerationType generationType, TypeName forcedReturnType, JavadocPart... javadocParts) {
    SQLiteDaoDefinition daoDefinition = method.getParent();
    SQLiteEntity entity = daoDefinition.getEntity();
    // if true, field must be associate to ben attributes
    // TypeName returnType = method.getReturnClass();
    TypeName returnTypeName = forcedReturnType;
    if (returnTypeName == null) {
        returnTypeName = method.getReturnClass();
    }
    ModelAnnotation annotation = method.getAnnotation(BindSqlSelect.class);
    // parameters
    List<String> paramNames = new ArrayList<String>();
    List<String> paramGetters = new ArrayList<String>();
    List<TypeName> paramTypeNames = new ArrayList<TypeName>();
    List<String> usedBeanPropertyNames = new ArrayList<>();
    // used method parameters
    Set<String> usedMethodParameters = new HashSet<String>();
    final One<String> whereJQL = new One<>("");
    final One<String> havingJQL = new One<>("");
    final One<String> groupJQL = new One<>("");
    final One<String> orderJQL = new One<>("");
    // extract parts of jql statement
    JQLChecker.getInstance().replaceVariableStatements(method, method.jql.value, new JQLReplaceVariableStatementListenerImpl() {

        @Override
        public String onWhere(String statement) {
            whereJQL.value0 = statement;
            return null;
        }

        @Override
        public String onOrderBy(String statement) {
            orderJQL.value0 = statement;
            return null;
        }

        @Override
        public String onHaving(String statement) {
            havingJQL.value0 = statement;
            return null;
        }

        @Override
        public String onGroup(String statement) {
            groupJQL.value0 = statement;
            return null;
        }
    });
    SqlAnalyzer analyzer = new SqlAnalyzer();
    // String whereSQL =
    // annotation.getAttribute(AnnotationAttributeType.WHERE);
    analyzer.execute(BaseProcessor.elementUtils, method, whereJQL.value0);
    paramGetters.addAll(analyzer.getParamGetters());
    paramNames.addAll(analyzer.getParamNames());
    paramTypeNames.addAll(analyzer.getParamTypeNames());
    usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames());
    usedMethodParameters.addAll(analyzer.getUsedMethodParameters());
    // String havingSQL =
    // annotation.getAttribute(AnnotationAttributeType.HAVING);
    analyzer.execute(BaseProcessor.elementUtils, method, havingJQL.value0);
    paramGetters.addAll(analyzer.getParamGetters());
    paramNames.addAll(analyzer.getParamNames());
    paramTypeNames.addAll(analyzer.getParamTypeNames());
    usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames());
    usedMethodParameters.addAll(analyzer.getUsedMethodParameters());
    // String groupBySQL =
    // annotation.getAttribute(AnnotationAttributeType.GROUP_BY);
    analyzer.execute(BaseProcessor.elementUtils, method, groupJQL.value0);
    paramGetters.addAll(analyzer.getParamGetters());
    paramNames.addAll(analyzer.getParamNames());
    paramTypeNames.addAll(analyzer.getParamTypeNames());
    usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames());
    usedMethodParameters.addAll(analyzer.getUsedMethodParameters());
    // String orderBySQL =
    // annotation.getAttribute(AnnotationAttributeType.ORDER_BY);
    analyzer.execute(BaseProcessor.elementUtils, method, orderJQL.value0);
    paramGetters.addAll(analyzer.getParamGetters());
    paramNames.addAll(analyzer.getParamNames());
    paramTypeNames.addAll(analyzer.getParamTypeNames());
    usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames());
    usedMethodParameters.addAll(analyzer.getUsedMethodParameters());
    // add as used parameter dynamic components too
    if (method.hasDynamicWhereConditions()) {
        AssertKripton.assertTrueOrInvalidMethodSignException(!usedMethodParameters.contains(method.dynamicWhereParameterName), method, " parameter %s is used like SQL parameter and dynamic WHERE condition.", method.dynamicOrderByParameterName);
        usedMethodParameters.add(method.dynamicWhereParameterName);
        if (method.hasDynamicWhereArgs()) {
            AssertKripton.assertTrueOrInvalidMethodSignException(!usedMethodParameters.contains(method.dynamicWhereArgsParameterName), method, " parameter %s is used like SQL parameter and dynamic WHERE ARGS condition.", method.dynamicWhereArgsParameterName);
            usedMethodParameters.add(method.dynamicWhereArgsParameterName);
        }
    }
    if (method.hasDynamicOrderByConditions()) {
        AssertKripton.assertTrueOrInvalidMethodSignException(!usedMethodParameters.contains(method.dynamicOrderByParameterName), method, " parameter %s is used like SQL parameter and dynamic ORDER BY condition.", method.dynamicOrderByParameterName);
        usedMethodParameters.add(method.dynamicOrderByParameterName);
    }
    if (method.hasDynamicPageSizeConditions()) {
        AssertKripton.assertTrueOrInvalidMethodSignException(!usedMethodParameters.contains(method.dynamicPageSizeName), method, " parameter %s is used like SQL parameter and dynamic page size of LIMIT condition.", method.dynamicPageSizeName);
        usedMethodParameters.add(method.dynamicPageSizeName);
    }
    // generate method signature
    if (generationType.generateMethodSign) {
        generateMethodSignature(method, methodBuilder, returnTypeName);
    }
    // generate javadoc
    JavadocUtility.generateJavaDocForSelect(methodBuilder, paramNames, method, annotation, fieldList, selectType, javadocParts);
    if (generationType.generateMethodContent) {
        SplittedSql splittedSql = SqlSelectBuilder.generateSQL(method, methodBuilder, false);
        // retrieve content values
        methodBuilder.addStatement("$T _contentValues=contentValues()", KriptonContentValues.class);
        if (method.hasDynamicParts()) {
            generateSQLBuild(method, methodBuilder, splittedSql);
            methodBuilder.addStatement("String _sql=_sqlBuilder.toString()");
        } else {
            String sqlName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, method.buildSQLName());
            String sql = SqlSelectBuilder.convertJQL2SQL(method, true);
            classBuilder.addField(FieldSpec.builder(String.class, sqlName, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("$S", sql).build());
            methodBuilder.addComment("query SQL is statically defined");
            methodBuilder.addStatement("String _sql=$L", sqlName);
        }
        // build where condition (common for every type of select)
        StringBuilder logArgsBuffer = new StringBuilder();
        methodBuilder.addComment("add where arguments");
        {
            String separator = "";
            TypeName paramTypeName;
            // String paramName;
            boolean nullable;
            int i = 0;
            boolean rawParameters;
            String beanName = null;
            beanName = method.findEntityProperty();
            for (String item : paramGetters) {
                rawParameters = paramNames.get(i).indexOf(".") == -1;
                methodBuilder.addCode("_contentValues.addWhereArgs(");
                logArgsBuffer.append(separator + "%s");
                paramTypeName = paramTypeNames.get(i);
                // code for query arguments
                nullable = TypeUtility.isNullable(paramTypeName);
                if (rawParameters) {
                    if (nullable && !method.hasAdapterForParam(item)) {
                        methodBuilder.addCode("($L==null?\"\":", item);
                    }
                    // check for string conversion
                    TypeUtility.beginStringConversion(methodBuilder, paramTypeName);
                    SQLTransformer.javaMethodParam2WhereConditions(methodBuilder, method, item, paramTypeName);
                    // check for string conversion
                    TypeUtility.endStringConversion(methodBuilder, paramTypeName);
                    if (nullable && !method.hasAdapterForParam(item)) {
                        methodBuilder.addCode(")");
                    }
                } else {
                    // eventually we take associated property
                    SQLProperty property = usedBeanPropertyNames.get(i) == null ? null : entity.get(usedBeanPropertyNames.get(i));
                    if (nullable && !(property != null) && !method.hasAdapterForParam(item)) {
                        methodBuilder.addCode("($L==null?\"\":", item);
                    }
                    // check for string conversion
                    TypeUtility.beginStringConversion(methodBuilder, paramTypeName);
                    // if (property != null) {
                    // SQLTransformer.javaProperty2WhereCondition(methodBuilder,
                    // method, item, paramTypeName, property);
                    // } else {
                    SQLTransformer.javaProperty2WhereCondition(methodBuilder, method, beanName, paramTypeName, property);
                    // }
                    // check for string conversion
                    TypeUtility.endStringConversion(methodBuilder, paramTypeName);
                    if (nullable && !(property != null) && !method.hasAdapterForParam(item)) {
                        methodBuilder.addCode(")");
                    }
                }
                separator = ", ";
                i++;
                methodBuilder.addCode(");\n");
            }
        }
        methodBuilder.addStatement("String[] _sqlArgs=_contentValues.whereArgsAsArray()");
        if (daoDefinition.isLogEnabled()) {
            // generate log section - BEGIN
            methodBuilder.addComment("log section BEGIN");
            methodBuilder.beginControlFlow("if (_context.isLogEnabled())");
            // manage log
            methodBuilder.addComment("manage log");
            methodBuilder.addStatement("$T.info(_sql)", Logger.class);
            // log for where parames
            SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);
            // generate log section - END
            methodBuilder.endControlFlow();
            methodBuilder.addComment("log section END");
        }
        if (generationType.generateCloseableCursor) {
            methodBuilder.beginControlFlow("try ($T _cursor = database().rawQuery(_sql, _sqlArgs))", Cursor.class);
        } else {
            methodBuilder.addStatement("$T _cursor = database().rawQuery(_sql, _sqlArgs)", Cursor.class);
        }
        if (daoDefinition.isLogEnabled()) {
            // generate log section - BEGIN
            methodBuilder.addComment("log section BEGIN");
            methodBuilder.beginControlFlow("if (_context.isLogEnabled())");
            methodBuilder.addCode("$T.info(\"Rows found: %s\",_cursor.getCount());\n", Logger.class);
            // generate log section - END
            methodBuilder.endControlFlow();
            methodBuilder.addComment("log section END");
        }
        switch(selectType) {
            case LISTENER_CURSOR:
                {
                    ClassName readCursorListenerToExclude = ClassName.get(OnReadCursorListener.class);
                    checkUnusedParameters(method, usedMethodParameters, readCursorListenerToExclude);
                }
                break;
            case LISTENER_BEAN:
                {
                    ParameterizedTypeName readBeanListenerToExclude = ParameterizedTypeName.get(ClassName.get(OnReadBeanListener.class), TypeName.get(entity.getElement().asType()));
                    checkUnusedParameters(method, usedMethodParameters, readBeanListenerToExclude);
                }
                break;
            default:
                checkUnusedParameters(method, usedMethodParameters, null);
                break;
        }
    }
}
Also used : JQLReplaceVariableStatementListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplaceVariableStatementListenerImpl) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) One(com.abubusoft.kripton.common.One) ArrayList(java.util.ArrayList) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) OnReadCursorListener(com.abubusoft.kripton.android.sqlite.OnReadCursorListener) SplittedSql(com.abubusoft.kripton.processor.sqlite.SqlSelectBuilder.SplittedSql) ModelAnnotation(com.abubusoft.kripton.processor.core.ModelAnnotation) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ClassName(com.squareup.javapoet.ClassName) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) HashSet(java.util.HashSet) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 19 with One

use of com.abubusoft.kripton.common.One in project kripton by xcesco.

the class AnnotationUtility method extractAsInt.

public static int extractAsInt(Element item, Class<? extends Annotation> annotationClass, AnnotationAttributeType attributeName) {
    final Elements elementUtils = BaseProcessor.elementUtils;
    final One<Integer> result = new One<Integer>();
    result.value0 = 0;
    extractString(elementUtils, item, annotationClass, attributeName, new OnAttributeFoundListener() {

        @Override
        public void onFound(String value) {
            result.value0 = Integer.parseInt(value);
        }
    });
    return result.value0;
}
Also used : One(com.abubusoft.kripton.common.One) Elements(javax.lang.model.util.Elements)

Example 20 with One

use of com.abubusoft.kripton.common.One in project kripton by xcesco.

the class AnnotationUtility method extractAsStringArray.

/**
 * Extract from an annotation of a method the attribute value specified. IF NO ELEMENT WAS FOUND, AN EMPTY LIST WILL RETURN.
 *
 * @param elementUtils
 * @param item
 * @param annotationClass
 * @param attributeName
 * @return attribute value extracted as class typeName
 */
public static List<String> extractAsStringArray(Element item, Class<? extends Annotation> annotationClass, AnnotationAttributeType attributeName) {
    final Elements elementUtils = BaseProcessor.elementUtils;
    final One<List<String>> result = new One<List<String>>(new ArrayList<String>());
    extractString(elementUtils, item, annotationClass, attributeName, new OnAttributeFoundListener() {

        @Override
        public void onFound(String value) {
            List<String> list = AnnotationUtility.extractAsArrayOfString(value);
            result.value0 = list;
        }
    });
    return result.value0;
}
Also used : One(com.abubusoft.kripton.common.One) ArrayList(java.util.ArrayList) List(java.util.List) Elements(javax.lang.model.util.Elements)

Aggregations

One (com.abubusoft.kripton.common.One)36 ArrayList (java.util.ArrayList)13 JQLReplacerListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)12 SQLProperty (com.abubusoft.kripton.processor.sqlite.model.SQLProperty)10 Elements (javax.lang.model.util.Elements)9 Where_stmtContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext)8 SQLiteDaoDefinition (com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)8 JQLChecker (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker)7 JQLReplaceVariableStatementListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplaceVariableStatementListenerImpl)7 JqlBaseListener (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener)7 Pair (com.abubusoft.kripton.common.Pair)5 SQLiteEntity (com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)5 Bind_parameterContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Bind_parameterContext)4 Projected_columnsContext (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Projected_columnsContext)4 TypeName (com.squareup.javapoet.TypeName)4 LinkedHashSet (java.util.LinkedHashSet)4 List (java.util.List)4 Test (org.junit.Test)4 BaseAndroidTest (base.BaseAndroidTest)3 TransactionResult (com.abubusoft.kripton.android.sqlite.TransactionResult)3