Search in sources :

Example 16 with SQLiteDaoDefinition

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition in project kripton by xcesco.

the class BindTableGenerator method visit.

private void visit(SQLiteDatabaseSchema schema, GeneratedTypeElement entity) throws Exception {
    int indexCounter = 0;
    // generate the class name that represents the table
    String classTableName = getTableClassName(entity.getSimpleName());
    PackageElement pkg = elementUtils.getPackageElement(entity.packageName);
    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);
        // every column is a long
        bufferTable.append(" " + SQLTransformer.lookup(TypeName.LONG).getColumnTypeAsString());
        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);
                }
            }
            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.getClassName().equals(TypeUtility.typeName(reference.getElement()))) {
                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 single column 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 : 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 17 with SQLiteDaoDefinition

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition in project kripton by xcesco.

the class InsertBeanHelper method generate.

@Override
public void generate(TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, boolean mapFields, SQLiteModelMethod method, TypeName returnType) {
    SQLiteDaoDefinition daoDefinition = method.getParent();
    SQLiteEntity entity = daoDefinition.getEntity();
    // retrieve content values
    if (method.jql.hasDynamicParts() || method.jql.containsSelectOperation) {
        methodBuilder.addStatement("$T _contentValues=contentValuesForUpdate()", KriptonContentValues.class);
    } else {
        String psName = method.buildPreparedStatementName();
        classBuilder.addField(FieldSpec.builder(TypeName.get(SQLiteStatement.class), psName, Modifier.PRIVATE, Modifier.STATIC).build());
        methodBuilder.beginControlFlow("if ($L==null)", psName);
        SqlBuilderHelper.generateSQLForStaticQuery(method, methodBuilder);
        methodBuilder.addStatement("$L = $T.compile(_context, _sql)", psName, KriptonDatabaseWrapper.class);
        methodBuilder.endControlFlow();
        methodBuilder.addStatement("$T _contentValues=contentValuesForUpdate($L)", KriptonContentValues.class, psName);
    }
    List<SQLProperty> listUsedProperty = CodeBuilderUtility.extractUsedProperties(methodBuilder, method, BindSqlInsert.class);
    CodeBuilderUtility.generateContentValuesFromEntity(BaseProcessor.elementUtils, method, BindSqlInsert.class, methodBuilder, null);
    ModelProperty primaryKey = entity.getPrimaryKey();
    // generate javadoc and query
    generateJavaDoc(methodBuilder, method, returnType, listUsedProperty, primaryKey);
    SqlBuilderHelper.generateLog(method, methodBuilder);
    methodBuilder.addComment("insert operation");
    if (method.jql.hasDynamicParts() || method.jql.containsSelectOperation) {
        // does not memorize compiled statement, it can vary every time
        // generate SQL for insert
        SqlBuilderHelper.generateSQLForInsertDynamic(method, methodBuilder);
        methodBuilder.addStatement("long result = $T.insert(_context, _sql, _contentValues)", KriptonDatabaseWrapper.class);
    } else {
        String psName = method.buildPreparedStatementName();
        methodBuilder.addStatement("long result = $T.insert($L, _contentValues)", KriptonDatabaseWrapper.class, psName);
    }
    if (method.getParent().getParent().generateRx) {
        GenericSQLHelper.generateSubjectNext(methodBuilder, SubjectType.INSERT);
    }
    if (primaryKey != null) {
        if (primaryKey.isPublicField()) {
            methodBuilder.addCode("$L.$L=result;\n", method.getParameters().get(0).value0, primaryKey.getName());
        } else {
            methodBuilder.addCode("$L.$L(result);\n", method.getParameters().get(0).value0, PropertyUtility.setter(typeName(entity.getElement()), primaryKey));
        }
    }
    // support for livedata
    if (daoDefinition.hasLiveData()) {
        methodBuilder.addComment("support for livedata");
        methodBuilder.addStatement(BindDaoBuilder.METHOD_NAME_REGISTRY_EVENT + "(result>0?1:0)");
    }
    // define return value
    if (returnType == TypeName.VOID) {
    } else if (TypeUtility.isTypeIncludedIn(returnType, String.class)) {
        methodBuilder.addCode("\n");
        methodBuilder.addCode("return String.valueOf(result);\n");
    } else if (TypeUtility.isTypeIncludedIn(returnType, Boolean.TYPE, Boolean.class)) {
        methodBuilder.addCode("\n");
        methodBuilder.addCode("return result!=-1;\n");
    } else if (TypeUtility.isTypeIncludedIn(returnType, Long.TYPE, Long.class)) {
        methodBuilder.addCode("\n");
        methodBuilder.addCode("return result;\n");
    } else if (TypeUtility.isTypeIncludedIn(returnType, Integer.TYPE, Integer.class)) {
        methodBuilder.addCode("\n");
        methodBuilder.addCode("return (int)result;\n");
    } else if (TypeUtility.isEquals(returnType, entity)) {
        methodBuilder.addCode("\n");
        methodBuilder.addCode("return $L;\n", method.getParameters().get(0).value0);
    } else {
        // more than one listener found
        throw (new InvalidMethodSignException(method, "invalid return type"));
    }
}
Also used : SQLiteStatement(android.database.sqlite.SQLiteStatement) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ModelProperty(com.abubusoft.kripton.processor.core.ModelProperty) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) InvalidMethodSignException(com.abubusoft.kripton.processor.exceptions.InvalidMethodSignException) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)

Example 18 with SQLiteDaoDefinition

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition in project kripton by xcesco.

the class SelectBeanListHelper method generateSpecializedPart.

/*
	 * (non-Javadoc)
	 * 
	 * @see com.abubusoft.kripton.processor.sqlite.SQLiteSelectBuilder.
	 * SelectCodeGenerator#generate(com.squareup.javapoet.MethodSpec.Builder)
	 */
@Override
public void generateSpecializedPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) {
    SQLiteDaoDefinition daoDefinition = method.getParent();
    SQLiteEntity entity = daoDefinition.getEntity();
    TypeName returnTypeName = method.getReturnClass();
    ParameterizedTypeName returnListName = (ParameterizedTypeName) returnTypeName;
    TypeName collectionClass;
    TypeName entityClass = typeName(entity.getElement());
    ClassName listClazzName = returnListName.rawType;
    collectionClass = defineCollection(listClazzName);
    methodBuilder.addCode("\n");
    if (TypeUtility.isTypeEquals(collectionClass, TypeUtility.typeName(ArrayList.class))) {
        methodBuilder.addCode("$T<$T> resultList=new $T<$T>(_cursor.getCount());\n", collectionClass, entityClass, collectionClass, entityClass);
    } else {
        methodBuilder.addCode("$T<$T> resultList=new $T<$T>();\n", collectionClass, entityClass, collectionClass, entityClass);
    }
    methodBuilder.addCode("$T resultBean=null;\n", entityClass);
    methodBuilder.addCode("\n");
    methodBuilder.beginControlFlow("if (_cursor.moveToFirst())");
    // generate index from columns
    methodBuilder.addCode("\n");
    {
        int i = 0;
        for (JQLProjection a : fieldList) {
            SQLProperty item = a.property;
            methodBuilder.addStatement("int index$L=_cursor.getColumnIndex($S)", (i++), item.columnName);
            if (item.hasTypeAdapter()) {
                methodBuilder.addStatement("$T $LAdapter=$T.getAdapter($T.class)", item.typeAdapter.getAdapterTypeName(), item.getName(), SQLTypeAdapterUtils.class, item.typeAdapter.getAdapterTypeName());
            }
        }
    }
    methodBuilder.addCode("\n");
    methodBuilder.beginControlFlow("do\n");
    methodBuilder.addCode("resultBean=new $T();\n\n", entityClass);
    // generate mapping
    int i = 0;
    for (JQLProjection a : fieldList) {
        SQLProperty item = a.property;
        if (item.isNullable()) {
            methodBuilder.addCode("if (!_cursor.isNull(index$L)) { ", i);
        }
        SQLTransformer.cursor2Java(methodBuilder, typeName(entity.getElement()), item, "resultBean", "_cursor", "index" + i + "");
        methodBuilder.addCode(";");
        if (item.isNullable()) {
            methodBuilder.addCode(" }");
        }
        methodBuilder.addCode("\n");
        i++;
    }
    methodBuilder.addCode("\n");
    methodBuilder.addCode("resultList.add(resultBean);\n");
    methodBuilder.endControlFlow("while (_cursor.moveToNext())");
    methodBuilder.endControlFlow();
    methodBuilder.addCode("\n");
    methodBuilder.addCode("return resultList;\n");
    // close try { open cursor
    methodBuilder.endControlFlow();
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) JQLProjection(com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLProjection) SQLTypeAdapterUtils(com.abubusoft.kripton.common.SQLTypeAdapterUtils) ClassName(com.squareup.javapoet.ClassName) ArrayList(java.util.ArrayList) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 19 with SQLiteDaoDefinition

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition in project kripton by xcesco.

the class CodeBuilderUtility method extractUsedProperties.

/**
 * Generate code necessary to put bean properties in content values map.
 * Return primary key
 * @param methodBuilder
 *            used to code generation
 * @param method
 * @param elementUtils
 * @param daoDefinition
 * @param alreadyUsedBeanPropertiesNames
 *            optional
 *
 * @return primary key.
 */
public static List<SQLProperty> extractUsedProperties(Builder methodBuilder, SQLiteModelMethod method, Class<? extends Annotation> annotationClazz) {
    SQLiteDaoDefinition daoDefinition = method.getParent();
    SQLiteEntity entity = daoDefinition.getEntity();
    List<SQLProperty> listPropertyInContentValue = new ArrayList<SQLProperty>();
    Set<String> foundColumns = JQLChecker.getInstance().extractColumnsToInsertOrUpdate(method, method.jql.value, entity);
    // for each property in entity except primaryKey and excluded properties
    for (SQLProperty item : entity.getCollection()) {
        if (foundColumns.size() > 0 && !foundColumns.contains(item.getName())) {
            continue;
        }
        // add property to list of used properties
        listPropertyInContentValue.add(item);
    }
    return listPropertyInContentValue;
}
Also used : SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ArrayList(java.util.ArrayList) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)

Example 20 with SQLiteDaoDefinition

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition in project kripton by xcesco.

the class BindDataSourceSubProcessor method analyzeForeignKey.

private void analyzeForeignKey(SQLiteDatabaseSchema schema) {
    for (SQLiteEntity entity : schema.getEntities()) {
        for (SQLProperty property : entity.getCollection()) {
            if (property.hasForeignKeyClassName()) {
                SQLiteEntity reference = schema.getEntity(property.foreignClassName);
                AssertKripton.asserTrueOrUnspecifiedBeanException(reference != null, schema, entity, property.foreignClassName);
                if (!entity.equals(reference)) {
                    entity.referedEntities.add(reference);
                }
            }
        }
    }
    for (SQLiteDaoDefinition dao : schema.getCollection()) {
        if (dao.getElement().getAnnotation(BindDaoMany2Many.class) != null) {
            ClassName entity1 = TypeUtility.className(AnnotationUtility.extractAsClassName(dao.getElement(), BindDaoMany2Many.class, AnnotationAttributeType.ENTITY_1));
            ClassName entity2 = TypeUtility.className(AnnotationUtility.extractAsClassName(dao.getElement(), BindDaoMany2Many.class, AnnotationAttributeType.ENTITY_2));
            // only if dao has an entity
            if (dao.getEntity() != null) {
                // check foreign key to entity1 and entity2
                checkForeignKeyForM2M(schema, dao.getEntity(), entity1);
                checkForeignKeyForM2M(schema, dao.getEntity(), entity2);
            }
        }
    }
}
Also used : BindDaoMany2Many(com.abubusoft.kripton.android.annotation.BindDaoMany2Many) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) ClassName(com.squareup.javapoet.ClassName) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)

Aggregations

SQLiteDaoDefinition (com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)43 SQLiteEntity (com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity)25 SQLProperty (com.abubusoft.kripton.processor.sqlite.model.SQLProperty)22 TypeName (com.squareup.javapoet.TypeName)21 Pair (com.abubusoft.kripton.common.Pair)9 JQLProjection (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLProjection)9 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)9 ArrayList (java.util.ArrayList)9 One (com.abubusoft.kripton.common.One)8 MethodSpec (com.squareup.javapoet.MethodSpec)8 InvalidMethodSignException (com.abubusoft.kripton.processor.exceptions.InvalidMethodSignException)6 ClassName (com.squareup.javapoet.ClassName)6 ModelAnnotation (com.abubusoft.kripton.processor.core.ModelAnnotation)5 JQLReplacerListenerImpl (com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl)5 ArrayTypeName (com.squareup.javapoet.ArrayTypeName)5 TypeSpec (com.squareup.javapoet.TypeSpec)5 SQLiteStatement (android.database.sqlite.SQLiteStatement)4 BindSqlUpdate (com.abubusoft.kripton.android.annotation.BindSqlUpdate)4 GeneratedTypeElement (com.abubusoft.kripton.processor.element.GeneratedTypeElement)4 JqlBaseListener (com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener)4