Search in sources :

Example 11 with JQLReplacerListenerImpl

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

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

the class BindTableGenerator method buldIndexes.

public static Pair<String, String> buldIndexes(final SQLiteEntity entity, boolean unique, int counter) {
    Pair<String, String> result = new Pair<>();
    result.value0 = "";
    result.value1 = "";
    ModelAnnotation annotationTable = entity.getAnnotation(BindTable.class);
    if (annotationTable == null)
        return result;
    List<String> indexes = null;
    String uniqueString;
    if (unique) {
        uniqueString = "UNIQUE ";
        indexes = annotationTable.getAttributeAsArray(AnnotationAttributeType.UNIQUE_INDEXES);
    } else {
        uniqueString = "";
        indexes = annotationTable.getAttributeAsArray(AnnotationAttributeType.INDEXES);
    }
    if (indexes == null || indexes.size() == 0)
        return result;
    // CREATE INDEX index_name ON tab_name (column1, column2)
    // Matcher matcher = patternIndex.matcher(rawIndexes);
    List<String> listCreateIndex = new ArrayList<>();
    List<String> listDropIndex = new ArrayList<>();
    for (String index : indexes) {
        String createIndex = String.format(" CREATE %sINDEX idx_%s_%s on %s (%s)", uniqueString, entity.getTableName(), counter++, entity.getTableName(), index);
        String dropIndex = String.format(" DROP INDEX IF EXISTS idx_%s_%s", entity.getTableName(), counter);
        final One<Integer> fieldCounter = new One<Integer>(0);
        createIndex = JQLChecker.getInstance().replace(new JQLContext() {

            @Override
            public String getContextDescription() {
                return "While table definition generation for entity " + entity.getName();
            }
        }, createIndex, new JQLReplacerListenerImpl(null) {

            @Override
            public String onColumnName(String columnName) {
                fieldCounter.value0++;
                SQLProperty property = entity.findPropertyByName(columnName);
                AssertKripton.assertTrue(property != null, "class '%s' in @%s(indexes) use unknown property '%s'", entity.getName(), BindTable.class.getSimpleName(), columnName);
                return property.columnName;
            }

            @Override
            public String onColumnFullyQualifiedName(String tableName, String columnName) {
                AssertKripton.fail("Inconsistent state");
                return null;
            }
        });
        AssertKripton.assertTrue(fieldCounter.value0 > 0, "class '%s' have @%s(indexes) with no well formed indexes", entity.getName(), BindTable.class.getSimpleName());
        listCreateIndex.add(createIndex);
        listDropIndex.add(dropIndex);
    }
    result.value0 = StringUtils.join(listCreateIndex, ";");
    result.value1 = StringUtils.join(listDropIndex, ";");
    return result;
}
Also used : JQLContext(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLContext) One(com.abubusoft.kripton.common.One) ArrayList(java.util.ArrayList) BindTable(com.abubusoft.kripton.android.annotation.BindTable) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) ModelAnnotation(com.abubusoft.kripton.processor.core.ModelAnnotation) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) Pair(com.abubusoft.kripton.common.Pair)

Example 13 with JQLReplacerListenerImpl

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

the class SqlSelectBuilder method convertJQL2SQL.

/**
 * @param schema
 * @param entity
 * @param method
 * @param jqlChecker
 * @return
 */
public static String convertJQL2SQL(final SQLiteModelMethod method, final boolean replaceWithQuestion) {
    JQLChecker jqlChecker = JQLChecker.getInstance();
    // convert jql to sql
    String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

        @Override
        public String onBindParameter(String bindParameterName) {
            if (replaceWithQuestion) {
                return "?";
            }
            return "${" + bindParameterName + "}";
        }

        @Override
        public String onColumnName(String columnName) {
            SQLProperty tempProperty = currentEntity.get(columnName);
            AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
            return tempProperty.columnName;
        }
    });
    return sql;
}
Also used : JQLChecker(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty)

Example 14 with JQLReplacerListenerImpl

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

the class JavadocUtility method generateJavaDocForSelect.

public static void generateJavaDocForSelect(MethodSpec.Builder methodBuilder, List<String> sqlParams, final SQLiteModelMethod method, ModelAnnotation annotation, Set<JQLProjection> fieldList, SelectType selectResultType, JavadocPart... javadocParts) {
    final SQLiteDaoDefinition daoDefinition = method.getParent();
    final SQLiteEntity entity = daoDefinition.getEntity();
    TypeName beanTypeName = TypeName.get(daoDefinition.getEntity().getElement().asType());
    String sql = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

        @Override
        public String onColumnName(String columnName) {
            SQLProperty tempProperty = daoDefinition.getEntity().get(columnName);
            AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
            return tempProperty.columnName;
        }
    });
    Set<JQLProjection> projectedColumns = JQLChecker.getInstance().extractProjections(method, method.jql.value, entity);
    methodBuilder.addJavadoc("<h2>Select SQL:</h2>\n\n", annotation.getSimpleName());
    methodBuilder.addJavadoc("<pre>$L</pre>", sql);
    methodBuilder.addJavadoc("\n\n");
    // there will be alway some projected column
    {
        methodBuilder.addJavadoc("<h2>Projected columns:</h2>\n");
        methodBuilder.addJavadoc("<dl>\n");
        for (JQLProjection column : projectedColumns) {
            // KRIPTON_DEBUG field info only it exists
            if (column.column != null) {
                methodBuilder.addJavadoc("\t<dt>$L</dt>", column.property.columnName);
                // SQLProperty attribute = fieldList.value1.get(i);
                methodBuilder.addJavadoc("<dd>is associated to bean's property <strong>$L</strong></dd>", column.column);
            } else {
                methodBuilder.addJavadoc("\t<dt>$L</dt>", column.expression);
                methodBuilder.addJavadoc("<dd>no bean's property is associated</dd>");
            }
            methodBuilder.addJavadoc("\n");
        }
        methodBuilder.addJavadoc("</dl>");
        methodBuilder.addJavadoc("\n\n");
    }
    // dynamic parts
    if (method.hasDynamicOrderByConditions() || method.hasDynamicWhereConditions() || method.hasDynamicPageSizeConditions()) {
        methodBuilder.addJavadoc("<h2>Method's parameters and associated dynamic parts:</h2>\n");
        methodBuilder.addJavadoc("<dl>\n");
        if (method.hasDynamicWhereConditions()) {
            methodBuilder.addJavadoc("<dt>$L</dt><dd>is part of where conditions resolved at runtime. In above SQL it is displayed as #{$L}</dd>\n", method.dynamicWhereParameterName, JQLDynamicStatementType.DYNAMIC_WHERE);
        }
        if (method.hasDynamicOrderByConditions()) {
            methodBuilder.addJavadoc("<dt>$L</dt>is part of order statement resolved at runtime. In above SQL it is displayed as #{$L}</dd>\n", method.dynamicOrderByParameterName, JQLDynamicStatementType.DYNAMIC_ORDER_BY);
        }
        if (method.hasDynamicPageSizeConditions()) {
            methodBuilder.addJavadoc("<dt>$L</dt>is part of limit statement resolved at runtime. In above SQL it is displayed as #{$L}</dd>\n", method.dynamicPageSizeName, JQLDynamicStatementType.DYNAMIC_PAGE_SIZE);
        }
        methodBuilder.addJavadoc("</dl>");
        methodBuilder.addJavadoc("\n\n");
    }
    // query parameters
    if (sqlParams.size() > 0) {
        methodBuilder.addJavadoc("<h2>Query's parameters:</h2>\n");
        methodBuilder.addJavadoc("<dl>\n");
        for (String param : sqlParams) {
            methodBuilder.addJavadoc("\t<dt>$L</dt><dd>is binded to method's parameter <strong>$L</strong></dd>\n", "${" + param + "}", method.findParameterNameByAlias(param));
        }
        methodBuilder.addJavadoc("</dl>");
        methodBuilder.addJavadoc("\n\n");
    }
    // method params
    ParameterSpec parameterSpec;
    for (Pair<String, TypeName> item : method.getParameters()) {
        parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
        methodBuilder.addJavadoc("@param $L\n", parameterSpec.name);
        if (beanTypeName.equals(item.value1)) {
            methodBuilder.addJavadoc("\tis used as $L\n", "${" + method.findParameterAliasByName(item.value0) + "}");
        } else if (TypeUtility.isTypeEquals(item.value1, ParameterizedTypeName.get(TypeUtility.className(OnReadBeanListener.class), beanTypeName))) {
            methodBuilder.addJavadoc("\tis the $T listener\n", beanTypeName);
        } else if (TypeUtility.isTypeEquals(item.value1, TypeUtility.className(OnReadCursorListener.class))) {
            methodBuilder.addJavadoc("\tis the cursor listener\n", beanTypeName);
        } else if (item.value0.equals(method.dynamicWhereParameterName)) {
            methodBuilder.addJavadoc("\tis used as <strong>dynamic WHERE statement</strong> and it is formatted by ({@link $T#format})\n", StringUtils.class);
        } else if (item.value0.equals(method.dynamicOrderByParameterName)) {
            methodBuilder.addJavadoc("\tis used as <strong>dynamic ORDER BY statement</strong> and it is formatted by ({@link $T#format})\n", StringUtils.class);
        } else if (item.value0.equals(method.dynamicPageSizeName)) {
            methodBuilder.addJavadoc("\tis used as <strong>dynamic LIMIT statement</strong> and it is formatted by ({@link $T#format})\n", StringUtils.class);
        } else {
            methodBuilder.addJavadoc("\tis binded to <code>$L</code>\n", "${" + method.findParameterAliasByName(item.value0) + "}");
        }
    }
    for (JavadocPart item : javadocParts) {
        if (item.javadocPartType != JavadocPartType.ADD_PARAMETER)
            continue;
        methodBuilder.addJavadoc("@param $L\n", item.name);
        methodBuilder.addJavadoc("\t$L\n", item.description);
    }
    for (JavadocPart item : javadocParts) {
        if (item.javadocPartType != JavadocPartType.RETURN)
            continue;
        methodBuilder.addJavadoc("@return $L\n", item.description);
        // override return
        return;
    }
    // return type
    switch(selectResultType) {
        case BEAN:
            methodBuilder.addJavadoc("@return selected bean or <code>null</code>.\n");
            break;
        case CURSOR:
            methodBuilder.addJavadoc("@return cursor. Closing the cursor is delegated to the calling code.\n");
            break;
        case LIST_BEAN:
            methodBuilder.addJavadoc("@return collection of bean or empty collection.\n");
            break;
        case LIST_SCALAR:
            methodBuilder.addJavadoc("@return collection of single value extracted by query.\n");
            break;
        case SCALAR:
            methodBuilder.addJavadoc("@return single value extracted by query.\n");
            break;
        case PAGED_RESULT:
            methodBuilder.addJavadoc("@return paginated result.\n");
            break;
        default:
            // case LISTENER_CURSOR:
            break;
    }
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) OnReadBeanListener(com.abubusoft.kripton.android.sqlite.OnReadBeanListener) ParameterSpec(com.squareup.javapoet.ParameterSpec) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) OnReadCursorListener(com.abubusoft.kripton.android.sqlite.OnReadCursorListener) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) JQLProjection(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLProjection) StringUtils(com.abubusoft.kripton.common.StringUtils) JavadocPart(com.abubusoft.kripton.processor.sqlite.AbstractSelectCodeGenerator.JavadocPart) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)

Example 15 with JQLReplacerListenerImpl

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

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