Search in sources :

Example 26 with SQLiteDaoDefinition

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

the class BindContentProviderBuilder method build.

public void build(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
    uriSet.clear();
    String dataSourceName = schema.getName();
    String dataSourceNameClazz = BindDataSourceBuilder.PREFIX + dataSourceName;
    String contentProviderName = PREFIX + dataSourceName.replace(BindDataSourceBuilder.SUFFIX, "") + SUFFIX;
    PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindContentProvider.class, packageName, contentProviderName);
    classBuilder = TypeSpec.classBuilder(contentProviderName).addModifiers(Modifier.PUBLIC).superclass(ContentProvider.class);
    classBuilder.addJavadoc("<p>This is the content provider generated for {@link $L}</p>\n\n", dataSourceName);
    classBuilder.addJavadoc("<h2>Content provider authority:</h2>\n");
    classBuilder.addJavadoc("<pre>$L</pre>\n\n", schema.contentProvider.authority);
    generateOnCreate(dataSourceNameClazz);
    generateOnShutdown(dataSourceNameClazz);
    // define static fields
    classBuilder.addField(FieldSpec.builder(String.class, "URI", Modifier.STATIC, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", schema.contentProviderUri()).addJavadoc("<p>content provider's URI.</p>\n<pre>$L</pre>\n", schema.contentProviderUri()).build());
    // instance
    classBuilder.addField(FieldSpec.builder(className(dataSourceNameClazz), "dataSource", Modifier.PRIVATE, Modifier.STATIC).addJavadoc("<p>datasource singleton</p>\n").build());
    classBuilder.addField(FieldSpec.builder(String.class, "AUTHORITY", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).addJavadoc("<p>Content provider authority</p>\n").initializer("$S", schema.contentProvider.authority).build());
    classBuilder.addField(FieldSpec.builder(UriMatcher.class, "sURIMatcher", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).addJavadoc("<p>URI matcher</p>\n").initializer("new $T($T.NO_MATCH)", UriMatcher.class, UriMatcher.class).build());
    Builder staticBuilder = CodeBlock.builder();
    Converter<String, String> daoConstantConverter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE);
    List<FieldSpec> listFieldUri = new ArrayList<>();
    List<FieldSpec> listFieldString = new ArrayList<>();
    List<FieldSpec> listFieldIndex = new ArrayList<>();
    List<FieldSpec> listFieldAlias = new ArrayList<>();
    for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
        String pathConstantName = "PATH_" + daoConstantConverter.convert(daoDefinition.getEntitySimplyClassName());
        if (!daoDefinition.contentProviderEnabled)
            continue;
        // define content provider paths
        for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
            if (!daoMethod.contentProviderEntryPathEnabled)
                continue;
            ContentEntry entry = uriSet.get(daoMethod.contentProviderEntryPathTemplate);
            if (entry == null) {
                entry = new ContentEntry(daoMethod.contentProviderEntryPath);
                uriSet.put(daoMethod.contentProviderEntryPathTemplate, entry);
                entry.path = daoMethod.contentProviderEntryPath;
                entry.uriTemplate = daoMethod.contentProviderEntryPathTemplate;
                // we finish later
                entry.pathCostant = pathConstantName;
                entry.pathIndex = pathConstantName;
            }
            switch(daoMethod.jql.operationType) {
                case INSERT:
                    AssertKripton.fail(entry.insert != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
                    entry.insert = daoMethod;
                    break;
                case UPDATE:
                    AssertKripton.fail(entry.update != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
                    entry.update = daoMethod;
                    break;
                case SELECT:
                    AssertKripton.fail(entry.select != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
                    entry.select = daoMethod;
                    break;
                case DELETE:
                    AssertKripton.fail(entry.delete != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
                    entry.delete = daoMethod;
                    break;
            }
        }
    }
    // sort uri set by
    List<Pair<String, ContentEntry>> listUriSet = new ArrayList<>();
    Pair<String, ContentEntry> item;
    for (Entry<String, ContentEntry> entry : uriSet.entrySet()) {
        item = new Pair<String, ContentEntry>(entry.getKey(), entry.getValue());
        listUriSet.add(item);
    }
    Comparator<Pair<String, ContentEntry>> c = new Comparator<Pair<String, ContentEntry>>() {

        @Override
        public int compare(Pair<String, ContentEntry> lhs, Pair<String, ContentEntry> rhs) {
            return lhs.value0.compareTo(rhs.value0);
        }
    };
    Collections.sort(listUriSet, c);
    Set<String> alreadyUsedName = new HashSet<String>();
    Converter<String, String> format = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE);
    int i = 1;
    for (Pair<String, ContentEntry> entry : listUriSet) {
        // define ordered part of attributes (after sort)
        entry.value1.pathCostant += "_" + i;
        entry.value1.pathIndex += "_" + i + "_INDEX";
        entry.value1.pathValue = i;
        // build class attributes
        listFieldString.add(FieldSpec.builder(String.class, entry.value1.pathCostant, Modifier.STATIC, Modifier.FINAL).initializer(CodeBlock.of("$S", entry.value1.uriTemplate)).build());
        listFieldIndex.add(FieldSpec.builder(Integer.TYPE, entry.value1.pathIndex, Modifier.STATIC, Modifier.FINAL).initializer(CodeBlock.of("$L", entry.value1.pathValue)).build());
        listFieldUri.add(FieldSpec.builder(Uri.class, "URI_" + entry.value1.pathCostant, Modifier.STATIC, Modifier.FINAL, Modifier.PRIVATE).addJavadoc("<p>Uri</p>\n").addJavadoc("<pre>$L/$L</pre>\n", schema.contentProviderUri().replace("*", "[*]"), entry.value1.uriTemplate.replace("*", "[*]")).initializer(CodeBlock.of("Uri.parse(URI+\"/$L\")", entry.value1.uriTemplate)).build());
        generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.delete);
        generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.insert);
        generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.select);
        generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.update);
        staticBuilder.addStatement("sURIMatcher.addURI(AUTHORITY, $L, $L)", entry.value1.pathCostant, entry.value1.pathIndex);
        i++;
    }
    for (FieldSpec f : listFieldUri) {
        classBuilder.addField(f);
    }
    for (FieldSpec f : listFieldString) {
        classBuilder.addField(f);
    }
    for (FieldSpec f : listFieldIndex) {
        classBuilder.addField(f);
    }
    for (FieldSpec f : listFieldAlias) {
        classBuilder.addField(f);
    }
    classBuilder.addStaticBlock(staticBuilder.build());
    generateQuery(schema);
    generateInsert(schema);
    generateUpdate(schema);
    generateDelete(schema);
    generateGetType(schema);
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : ContentProvider(android.content.ContentProvider) BindContentProvider(com.abubusoft.kripton.android.annotation.BindContentProvider) Builder(com.squareup.javapoet.CodeBlock.Builder) ArrayList(java.util.ArrayList) Uri(android.net.Uri) FieldSpec(com.squareup.javapoet.FieldSpec) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) Comparator(java.util.Comparator) SQLiteModelMethod(com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod) PackageElement(javax.lang.model.element.PackageElement) Pair(com.abubusoft.kripton.common.Pair) HashSet(java.util.HashSet) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 27 with SQLiteDaoDefinition

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

the class BindDataSourceBuilder method generateDataSourceSingleThread.

private void generateDataSourceSingleThread(SQLiteDatabaseSchema schema, String dataSourceName) {
    // class DataSourceSingleThread
    String daoFactoryName = BindDaoFactoryBuilder.generateDaoFactoryName(schema);
    TypeSpec.Builder clazzBuilder = TypeSpec.classBuilder(DATA_SOURCE_SINGLE_THREAD_NAME).addSuperinterface(TypeUtility.typeName(daoFactoryName));
    // _context field
    clazzBuilder.addField(FieldSpec.builder(SQLContextInSessionImpl.class, "_context", Modifier.PRIVATE).build());
    // constructor
    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
    constructorBuilder.addStatement("_context=new $T($L.this)", SQLContextInSessionImpl.class, dataSourceName);
    // all dao
    for (SQLiteDaoDefinition dao : schema.getCollection()) {
        TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);
        // dao with external connections
        {
            String daoFieldName = extractDaoFieldNameForInternalDataSource(dao);
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("get" + dao.getName()).addModifiers(Modifier.PUBLIC).addJavadoc("\nretrieve dao $L\n", dao.getName()).returns(daoImplName);
            methodBuilder.beginControlFlow("if ($L==null)", daoFieldName);
            methodBuilder.addStatement("$L=new $T(_context)", daoFieldName, daoImplName);
            methodBuilder.endControlFlow();
            methodBuilder.addStatement("return $L", daoFieldName);
            clazzBuilder.addMethod(methodBuilder.build());
            clazzBuilder.addField(FieldSpec.builder(daoImplName, daoFieldName, Modifier.PROTECTED).build());
        }
    }
    // constructor
    clazzBuilder.addMethod(constructorBuilder.build());
    // onSessionOpened
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionOpened").addModifiers(Modifier.PROTECTED).returns(Void.TYPE);
        if (schema.hasLiveData()) {
            methodBuilder.addComment("support for live data");
            methodBuilder.addStatement("_context.onSessionOpened()");
        }
        clazzBuilder.addMethod(methodBuilder.build());
    }
    // onSessionClear
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionClear").addModifiers(Modifier.PROTECTED).returns(Void.TYPE);
        if (schema.hasLiveData()) {
            methodBuilder.addComment("support for live data");
            methodBuilder.addStatement("_context.onSessionOpened()");
        }
        clazzBuilder.addMethod(methodBuilder.build());
    }
    // onSessionClosed
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionClosed").addModifiers(Modifier.PROTECTED).returns(Void.TYPE);
        if (schema.hasLiveData()) {
            methodBuilder.addComment("support for live data");
            methodBuilder.addStatement("$T daosWithEvents=_context.onSessionClosed()", ParameterizedTypeName.get(Set.class, Integer.class));
            for (SQLiteDaoDefinition dao : schema.getCollection()) {
                // TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);
                String daoFieldName = extractDaoFieldNameForInternalDataSource(dao);
                methodBuilder.beginControlFlow("if ($L!=null && daosWithEvents.contains($L))", daoFieldName, dao.daoUidName);
                methodBuilder.addStatement("$L.invalidateLiveData()", daoFieldName);
                methodBuilder.endControlFlow();
            }
        }
        clazzBuilder.addMethod(methodBuilder.build());
    }
    // build method bindToThread
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("bindToThread").addModifiers(Modifier.PUBLIC).returns(TypeUtility.typeName(DATA_SOURCE_SINGLE_THREAD_NAME));
        // methodBuilder.addStatement("_context.bindToThread()");
        methodBuilder.addStatement("return this");
        clazzBuilder.addMethod(methodBuilder.build());
        // build single thread daoFactory used in transaction
        classBuilder.addField(FieldSpec.builder(TypeUtility.typeName(DATA_SOURCE_SINGLE_THREAD_NAME), "_daoFactorySingleThread", Modifier.PROTECTED).addJavadoc("Used only in transactions (that can be executed one for time\n").initializer("new DataSourceSingleThread()").build());
    }
    classBuilder.addType(clazzBuilder.build());
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) MethodSpec(com.squareup.javapoet.MethodSpec) Builder(com.squareup.javapoet.FieldSpec.Builder) TypeSpec(com.squareup.javapoet.TypeSpec) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition)

Example 28 with SQLiteDaoDefinition

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

the class BindDataSourceBuilder method buildDataSource.

public void buildDataSource(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema, String daoFactoryName) throws Exception {
    ClassName daoFactoryClazz = className(daoFactoryName);
    Converter<String, String> convert = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
    ClassName dataSourceClassName = generateDataSourceName(schema);
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, dataSourceClassName);
    classBuilder = TypeSpec.classBuilder(dataSourceClassName.simpleName()).addModifiers(Modifier.PUBLIC).superclass(AbstractDataSource.class).addSuperinterface(daoFactoryClazz).addSuperinterface(TypeUtility.typeName(schema.getElement().asType()));
    classBuilder.addJavadoc("<p>\n");
    classBuilder.addJavadoc("Represents implementation of datasource $L.\n", schema.getName());
    classBuilder.addJavadoc("This class expose database interface through Dao attribute.\n", schema.getName());
    classBuilder.addJavadoc("</p>\n\n");
    JavadocUtility.generateJavadocGeneratedBy(classBuilder);
    classBuilder.addJavadoc("@see $T\n", className(schema.getName()));
    classBuilder.addJavadoc("@see $T\n", daoFactoryClazz);
    for (SQLiteDaoDefinition dao : schema.getCollection()) {
        TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);
        classBuilder.addJavadoc("@see $T\n", dao.getElement());
        classBuilder.addJavadoc("@see $T\n", daoImplName);
        String entity = BindDataSourceSubProcessor.generateEntityName(dao, dao.getEntity());
        classBuilder.addJavadoc("@see $T\n", TypeUtility.typeName(entity));
    }
    // define static fields
    // instance
    classBuilder.addField(FieldSpec.builder(dataSourceClassName, "instance", Modifier.STATIC, Modifier.VOLATILE).addJavadoc("<p>datasource singleton</p>\n").build());
    classBuilder.addField(FieldSpec.builder(Object.class, "mutex", Modifier.STATIC, Modifier.FINAL, Modifier.PRIVATE).addJavadoc("<p>Mutex to manage multithread access to instance</p>\n").initializer("new Object()").build());
    for (SQLiteDaoDefinition dao : schema.getCollection()) {
        // TypeName daoInterfaceName =
        // BindDaoBuilder.daoInterfaceTypeName(dao);
        TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);
        classBuilder.addField(FieldSpec.builder(daoImplName, convert.convert(dao.getName()), Modifier.PROTECTED).addJavadoc("<p>dao instance</p>\n").initializer("new $T(context)", daoImplName).build());
        // dao with connections
        {
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("get" + dao.getName()).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(BindDaoBuilder.daoTypeName(dao));
            methodBuilder.addCode("return $L;\n", convert.convert(dao.getName()));
            classBuilder.addMethod(methodBuilder.build());
        }
    }
    if (schema.generateRx) {
        generateRx(dataSourceClassName, daoFactoryName);
        for (SQLiteDaoDefinition dao : schema.getCollection()) {
            // subject
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, dao.getEntitySimplyClassName() + "Subject")).addModifiers(Modifier.PUBLIC);
            methodBuilder.addStatement("return $L.subject()", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, convert.convert(dao.getName()))).returns(ParameterizedTypeName.get(PublishSubject.class, SQLiteEvent.class));
            classBuilder.addMethod(methodBuilder.build());
        }
    }
    // interface
    generateMethodExecuteTransaction(daoFactoryName);
    generateMethodExecuteBatch(daoFactoryName);
    // generate instance
    generateInstanceOrBuild(schema, dataSourceClassName.simpleName(), true);
    // generate open
    generateOpen(dataSourceClassName.simpleName());
    // generate openReadOnly
    generateOpenReadOnly(dataSourceClassName.simpleName());
    // generate constructor
    generateConstructor(schema);
    // before use entities, order them with dependencies respect
    List<SQLiteEntity> orderedEntities = generateOrderedEntitiesList(schema);
    // onCreate
    boolean useForeignKey = generateOnCreate(schema, orderedEntities);
    // onUpgrade
    generateOnUpgrade(schema, orderedEntities);
    // onConfigure
    generateOnConfigure(useForeignKey);
    // generate
    generateDaoUids(classBuilder, schema);
    // 
    // generate prepared statement cleaner
    {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("clearCompiledStatements").addModifiers(Modifier.PUBLIC).returns(Void.TYPE);
        for (SQLiteDaoDefinition dao : schema.getCollection()) {
            methodBuilder.addStatement("$T.clearCompiledStatements()", TypeUtility.className(dao.getElement().getQualifiedName().toString() + "Impl"));
        }
        classBuilder.addMethod(methodBuilder.build());
    }
    // generate single thread datasource
    generateDataSourceSingleThread(schema, dataSourceClassName.simpleName());
    // generate build
    generateInstanceOrBuild(schema, dataSourceClassName.simpleName(), false);
    {
        Builder f = FieldSpec.builder(ArrayTypeName.of(SQLiteTable.class), "TABLES", Modifier.FINAL, Modifier.STATIC).addJavadoc("List of tables compose datasource\n");
        com.squareup.javapoet.CodeBlock.Builder c = CodeBlock.builder();
        String s = "";
        c.add("{");
        for (SQLiteEntity entity : schema.getEntities()) {
            String tableName = BindTableGenerator.getTableClassName(entity.getName());
            c.add(s + "new $T()", TypeUtility.className(tableName));
            s = ", ";
        }
        for (GeneratedTypeElement entity : schema.generatedEntities) {
            String tableName = BindTableGenerator.getTableClassName(entity.getQualifiedName());
            c.add(s + "new $T()", TypeUtility.className(tableName));
            s = ", ";
        }
        c.add("}");
        f.initializer(c.build());
        classBuilder.addField(f.build());
        classBuilder.addMethod(MethodSpec.methodBuilder("tables").addJavadoc("List of tables compose datasource:\n").addModifiers(Modifier.PUBLIC, Modifier.STATIC).addStatement("return TABLES").returns(ArrayTypeName.of(SQLiteTable.class)).build());
    }
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, dataSourceClassName.packageName(), typeSpec);
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) MethodSpec(com.squareup.javapoet.MethodSpec) Builder(com.squareup.javapoet.FieldSpec.Builder) SQLiteTable(com.abubusoft.kripton.android.sqlite.SQLiteTable) AbstractDataSource(com.abubusoft.kripton.android.sqlite.AbstractDataSource) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) SQLiteEvent(com.abubusoft.kripton.android.sqlite.SQLiteEvent) GeneratedTypeElement(com.abubusoft.kripton.processor.element.GeneratedTypeElement) PublishSubject(io.reactivex.subjects.PublishSubject) ClassName(com.squareup.javapoet.ClassName) SQLiteEntity(com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 29 with SQLiteDaoDefinition

use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition 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 30 with SQLiteDaoDefinition

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

the class ModifyBeanHelper method generateWhereCondition.

/**
 * @param methodBuilder
 * @param method
 * @param analyzer
 */
public void generateWhereCondition(MethodSpec.Builder methodBuilder, SQLiteModelMethod method, SqlAnalyzer analyzer) {
    SQLiteDaoDefinition daoDefinition = method.getParent();
    SQLiteEntity entity = daoDefinition.getEntity();
    String beanParamName = method.getParameters().get(0).value0;
    SQLProperty property;
    boolean nullable;
    TypeName beanClass = typeName(entity.getElement());
    for (String item : analyzer.getUsedBeanPropertyNames()) {
        property = entity.findPropertyByName(item);
        // methodBuilder.addCode("_sqlWhereParams.add(");
        methodBuilder.addCode("_contentValues.addWhereArgs(");
        nullable = TypeUtility.isNullable(property);
        if (nullable && !(property.hasTypeAdapter())) {
            // transform null in ""
            methodBuilder.addCode("($L==null?\"\":", getter(beanParamName, beanClass, property));
        }
        // check for string conversion
        TypeUtility.beginStringConversion(methodBuilder, property);
        SQLTransformer.javaProperty2WhereCondition(methodBuilder, method, beanParamName, beanClass, property);
        // check for string conversion
        TypeUtility.endStringConversion(methodBuilder, property);
        if (nullable && !(property.hasTypeAdapter())) {
            methodBuilder.addCode(")");
        }
        methodBuilder.addCode(");\n");
    }
}
Also used : TypeName(com.squareup.javapoet.TypeName) SQLProperty(com.abubusoft.kripton.processor.sqlite.model.SQLProperty) 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