Search in sources :

Example 11 with Pair

use of com.abubusoft.kripton.common.Pair 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 12 with Pair

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

the class BindTableGenerator method visit.

@Override
public void visit(SQLiteDatabaseSchema schema, SQLiteEntity entity) throws Exception {
    int indexCounter = 0;
    // generate the class name that represents the table
    String classTableName = getTableClassName(entity.getSimpleName());
    PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, classTableName);
    classBuilder = TypeSpec.classBuilder(classTableName).addModifiers(Modifier.PUBLIC).addSuperinterface(SQLiteTable.class);
    BindTypeContext context = new BindTypeContext(classBuilder, TypeUtility.typeName(packageName, classTableName), Modifier.STATIC, Modifier.PRIVATE);
    // javadoc for class
    classBuilder.addJavadoc("<p>");
    classBuilder.addJavadoc("\nEntity <code>$L</code> is associated to table <code>$L</code>\n", entity.getSimpleName(), entity.getTableName());
    classBuilder.addJavadoc("This class represents table associated to entity.\n");
    classBuilder.addJavadoc("</p>\n");
    JavadocUtility.generateJavadocGeneratedBy(classBuilder);
    classBuilder.addJavadoc(" @see $T\n", TypeUtility.className(entity.getName()));
    {
        // @formatter:off
        // table_name
        FieldSpec fieldSpec = FieldSpec.builder(String.class, "TABLE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("\"$L\"", entity.getTableName()).addJavadoc("Costant represents typeName of table $L\n", entity.getTableName()).build();
        classBuilder.addField(fieldSpec);
    // @formatter:on
    }
    StringBuilder bufferTable = new StringBuilder();
    StringBuilder bufferForeignKey = new StringBuilder();
    // shared between create table and drop table
    StringBuilder bufferIndexesCreate = new StringBuilder();
    StringBuilder bufferDropTable = new StringBuilder();
    StringBuilder bufferIndexesDrop = new StringBuilder();
    bufferTable.append("CREATE TABLE " + entity.getTableName());
    // define column typeName set
    String separator = "";
    bufferTable.append(" (");
    // for each column, that need to be persisted on table
    for (SQLProperty item : entity.getCollection()) {
        bufferTable.append(separator);
        bufferTable.append(item.columnName);
        bufferTable.append(" " + SQLTransformer.columnTypeAsString(item));
        switch(item.columnType) {
            case PRIMARY_KEY:
                bufferTable.append(" PRIMARY KEY AUTOINCREMENT");
                break;
            case UNIQUE:
                bufferTable.append(" UNIQUE");
                break;
            case INDEXED:
                bufferIndexesCreate.append(String.format(" CREATE INDEX idx_%s_%s ON %s(%s);", entity.getTableName(), item.columnName, entity.getTableName(), item.columnName));
                bufferIndexesDrop.append(String.format(" DROP INDEX IF EXISTS idx_%s_%s;", entity.getTableName(), item.columnName));
                break;
            case STANDARD:
                break;
        }
        boolean nullable = item.isNullable();
        // null
        if (!nullable && item.columnType != ColumnType.PRIMARY_KEY) {
            bufferTable.append(" NOT NULL");
        }
        // foreign key
        String foreignClassName = item.foreignClassName;
        if (item.hasForeignKeyClassName()) {
            SQLiteEntity reference = model.getEntity(foreignClassName);
            if (reference == null) {
                // check if we have a DAO associated into DataSource
                // definition
                boolean found = false;
                for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
                    if (daoDefinition.getEntityClassName().equals(foreignClassName)) {
                        found = true;
                    }
                }
                if (!found) {
                    throw new NoDaoElementFound(schema, TypeUtility.className(foreignClassName));
                } else {
                    throw new InvalidBeanTypeException(item, foreignClassName);
                }
            }
            // long/Long
            if (!TypeUtility.isTypeIncludedIn(item.getPropertyType().getTypeName(), Long.class, Long.TYPE)) {
                throw new InvalidForeignKeyTypeException(item);
            }
            bufferForeignKey.append(", FOREIGN KEY(" + item.columnName + ") REFERENCES " + reference.getTableName() + "(" + reference.getPrimaryKey().columnName + ")");
            if (item.onDeleteAction != ForeignKeyAction.NO_ACTION) {
                bufferForeignKey.append(" ON DELETE " + item.onDeleteAction.toString().replaceAll("_", " "));
            }
            if (item.onUpdateAction != ForeignKeyAction.NO_ACTION) {
                bufferForeignKey.append(" ON UPDATE " + item.onUpdateAction.toString().replaceAll("_", " "));
            }
            // Same entity can not be own dependency.
            if (!entity.equals(reference)) {
                entity.referedEntities.add(reference);
            }
        }
        separator = ", ";
    }
    // add foreign key
    bufferTable.append(bufferForeignKey.toString());
    bufferTable.append(");");
    // add indexes creation one table
    if (bufferIndexesCreate.length() > 0) {
        bufferTable.append(bufferIndexesCreate.toString());
    }
    // add multicolumn indexes (UNIQUE)
    {
        Pair<String, String> multiIndexes = buldIndexes(entity, true, indexCounter);
        if (!StringUtils.isEmpty(multiIndexes.value0)) {
            bufferTable.append(multiIndexes.value0 + ";");
            bufferIndexesDrop.append(multiIndexes.value1 + ";");
        }
    }
    // add multicolumn indexes (NOT UNIQUE)
    {
        Pair<String, String> multiIndexes = buldIndexes(entity, false, indexCounter);
        if (!StringUtils.isEmpty(multiIndexes.value0)) {
            bufferTable.append(multiIndexes.value0 + ";");
            bufferIndexesDrop.append(multiIndexes.value1 + ";");
        }
    }
    {
        // create table SQL
        // @formatter:off
        FieldSpec.Builder fieldSpec = FieldSpec.builder(String.class, "CREATE_TABLE_SQL").addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC);
        // @formatter:on
        // @formatter:off
        fieldSpec.addJavadoc("<p>\nDDL to create table $L\n</p>\n", entity.getTableName());
        fieldSpec.addJavadoc("\n<pre>$L</pre>\n", bufferTable.toString());
        // @formatter:on
        classBuilder.addField(fieldSpec.initializer("$S", bufferTable.toString()).build());
    }
    // with tables
    if (bufferIndexesDrop.length() > 0) {
        bufferDropTable.append(bufferIndexesDrop.toString());
    }
    bufferDropTable.append("DROP TABLE IF EXISTS " + entity.getTableName() + ";");
    {
        // @formatter:off
        FieldSpec fieldSpec = FieldSpec.builder(String.class, "DROP_TABLE_SQL").addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC).initializer("$S", bufferDropTable.toString()).addJavadoc("<p>\nDDL to drop table $L\n</p>\n", entity.getTableName()).addJavadoc("\n<pre>$L</pre>\n", bufferDropTable.toString()).build();
        // @formatter:on
        classBuilder.addField(fieldSpec);
    }
    // define column typeName set
    for (ModelProperty item : entity.getCollection()) {
        item.accept(this);
    }
    ManagedPropertyPersistenceHelper.generateFieldPersistance(context, entity.getCollection(), PersistType.BYTE, true, Modifier.STATIC, Modifier.PUBLIC);
    model.sqlForCreate.add(bufferTable.toString());
    model.sqlForDrop.add(bufferDropTable.toString());
    generateColumnsArray(entity);
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : InvalidForeignKeyTypeException(com.abubusoft.kripton.processor.exceptions.InvalidForeignKeyTypeException) Builder(com.squareup.javapoet.FieldSpec.Builder) InvalidBeanTypeException(com.abubusoft.kripton.processor.exceptions.InvalidBeanTypeException) SQLiteTable(com.abubusoft.kripton.android.sqlite.SQLiteTable) BindTypeContext(com.abubusoft.kripton.processor.bind.BindTypeContext) FieldSpec(com.squareup.javapoet.FieldSpec) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) NoDaoElementFound(com.abubusoft.kripton.processor.exceptions.NoDaoElementFound) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ModelProperty(com.abubusoft.kripton.processor.core.ModelProperty) PackageElement(javax.lang.model.element.PackageElement) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) Pair(com.abubusoft.kripton.common.Pair) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 13 with Pair

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

the class JQLChecker method prepareParser.

protected Pair<ParserRuleContext, CommonTokenStream> prepareParser(final JQLContext jqlContext, final String jql) {
    JqlLexer lexer = new JqlLexer(CharStreams.fromString(jql));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    JqlParser parser = new JqlParser(tokens);
    parser.removeErrorListeners();
    parser.addErrorListener(new JQLBaseErrorListener() {

        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            AssertKripton.assertTrue(false, jqlContext.getContextDescription() + ": unespected char at pos %s of SQL '%s'", charPositionInLine, jql);
        }
    });
    ParserRuleContext context = parser.parse();
    return new Pair<>(context, tokens);
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) JqlLexer(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlLexer) JqlParser(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser) RecognitionException(org.antlr.v4.runtime.RecognitionException) Pair(com.abubusoft.kripton.common.Pair)

Example 14 with Pair

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

the class JQLChecker method prepareVariableStatement.

/**
 * <p>
 * Parse the variable parts of a SQL:
 * </p>
 *
 * <ul>
 * <li>where_stmt</li>
 * <li>group_stmt</li>
 * <li>having_stmt</li>
 * <li>order_stmt</li>
 * <li>limit_stmt</li>
 * <li>offset_stmt</li>
 * </ul>
 *
 * @param jql
 * @return
 */
protected Pair<ParserRuleContext, CommonTokenStream> prepareVariableStatement(final JQLContext jqlContext, final String jql) {
    JqlLexer lexer = new JqlLexer(CharStreams.fromString(jql));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    JqlParser parser = new JqlParser(tokens);
    parser.removeErrorListeners();
    parser.addErrorListener(new JQLBaseErrorListener() {

        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            AssertKripton.assertTrue(false, jqlContext.getContextDescription() + ": unespected char at pos %s of JQL '%s'", charPositionInLine, jql);
        }
    });
    ParserRuleContext context = parser.parse_variable();
    return new Pair<>(context, tokens);
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) JqlLexer(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlLexer) JqlParser(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser) RecognitionException(org.antlr.v4.runtime.RecognitionException) Pair(com.abubusoft.kripton.common.Pair)

Example 15 with Pair

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

the class SqlBuilderHelper method orderContentValues.

public static List<Pair<String, TypeName>> orderContentValues(final SQLiteModelMethod method, final List<Pair<String, TypeName>> updateableParams) {
    final List<Pair<String, TypeName>> result = new ArrayList<Pair<String, TypeName>>();
    JQLChecker checker = JQLChecker.getInstance();
    final One<Boolean> inserMode = new One<Boolean>(false);
    checker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

        // used in update
        @Override
        public String onColumnNameToUpdate(String columnName) {
            String column = currentEntity.findPropertyByName(columnName).columnName;
            for (Pair<String, TypeName> item : updateableParams) {
                String paramNameInQuery = method.findParameterAliasByName(item.value0);
                if (paramNameInQuery.equalsIgnoreCase(columnName)) {
                    result.add(item);
                    break;
                }
            }
            return column;
        }

        // used in insert
        @Override
        public void onColumnNameSetBegin(Column_name_setContext ctx) {
            inserMode.value0 = true;
        }

        @Override
        public void onColumnNameSetEnd(Column_name_setContext ctx) {
            inserMode.value0 = false;
        }

        @Override
        public String onColumnName(String columnName) {
            if (!inserMode.value0)
                return columnName;
            String column = currentEntity.findPropertyByName(columnName).columnName;
            for (Pair<String, TypeName> item : updateableParams) {
                String paramNameInQuery = method.findParameterAliasByName(item.value0);
                if (paramNameInQuery.equalsIgnoreCase(columnName)) {
                    result.add(item);
                    break;
                }
            }
            return column;
        }
    });
    return result;
}
Also used : Column_name_setContext(com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Column_name_setContext) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) JQLChecker(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLChecker) JQLReplacerListenerImpl(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl) One(com.abubusoft.kripton.common.One) ArrayList(java.util.ArrayList) Pair(com.abubusoft.kripton.common.Pair)

Aggregations

Pair (com.abubusoft.kripton.common.Pair)19 SQLProperty (com.abubusoft.kripton.processor.sqlite.model.SQLProperty)9 SQLiteDaoDefinition (com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)9 ArrayList (java.util.ArrayList)9 TypeName (com.squareup.javapoet.TypeName)8 JQLReplacerListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)6 SQLiteEntity (com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)6 One (com.abubusoft.kripton.common.One)5 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)5 ParserRuleContext (org.antlr.v4.runtime.ParserRuleContext)5 RecognitionException (org.antlr.v4.runtime.RecognitionException)5 InvalidMethodSignException (com.abubusoft.kripton.processor.exceptions.InvalidMethodSignException)4 TypeSpec (com.squareup.javapoet.TypeSpec)4 PropertyNotFoundException (com.abubusoft.kripton.processor.exceptions.PropertyNotFoundException)3 JqlLexer (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlLexer)3 JqlParser (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser)3 FieldSpec (com.squareup.javapoet.FieldSpec)3 PackageElement (javax.lang.model.element.PackageElement)3 SQLiteStatement (android.database.sqlite.SQLiteStatement)2 SQLiteTable (com.abubusoft.kripton.android.sqlite.SQLiteTable)2