use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity in project kripton by xcesco.
the class BindDataSourceBuilder method generateOnCreate.
/**
* @param schema
* @param orderedEntities
*/
private boolean generateOnCreate(SQLiteDatabaseSchema schema, List<SQLiteEntity> orderedEntities) {
boolean useForeignKey = false;
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onCreate").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
methodBuilder.addParameter(SQLiteDatabase.class, "database");
methodBuilder.addJavadoc("onCreate\n");
methodBuilder.addCode("// generate tables\n");
if (schema.isLogEnabled()) {
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (this.logEnabled)");
methodBuilder.beginControlFlow("if (options.inMemory)");
methodBuilder.addStatement("$T.info(\"Create database in memory\")", Logger.class);
methodBuilder.nextControlFlow("else");
methodBuilder.addStatement("$T.info(\"Create database '%s' version %s\",this.name, this.version)", Logger.class);
methodBuilder.endControlFlow();
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
}
for (SQLiteEntity item : orderedEntities) {
if (schema.isLogEnabled()) {
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (this.logEnabled)");
methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class, BindTableGenerator.tableClassName(null, item));
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
}
methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)", BindTableGenerator.tableClassName(null, item));
if (item.referedEntities.size() > 0) {
useForeignKey = true;
}
}
// if we have generated entities, we use foreign key for sure
if (schema.generatedEntities.size() > 0)
useForeignKey = true;
for (GeneratedTypeElement item : schema.generatedEntities) {
if (schema.isLogEnabled()) {
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (this.logEnabled)");
methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class, TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
}
methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)", TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
}
methodBuilder.beginControlFlow("if (options.databaseLifecycleHandler != null)");
methodBuilder.addStatement("options.databaseLifecycleHandler.onCreate(database)");
methodBuilder.endControlFlow();
methodBuilder.addStatement("justCreated=true");
classBuilder.addMethod(methodBuilder.build());
return useForeignKey;
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity in project kripton by xcesco.
the class BindDataSourceBuilder method generateOnUpgrade.
/**
* @param schema
* @param orderedEntities
*/
private void generateOnUpgrade(SQLiteDatabaseSchema schema, List<SQLiteEntity> orderedEntities) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onUpgrade").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
methodBuilder.addParameter(SQLiteDatabase.class, "database");
methodBuilder.addParameter(Integer.TYPE, "previousVersion");
methodBuilder.addParameter(Integer.TYPE, "currentVersion");
methodBuilder.addJavadoc("onUpgrade\n");
Collections.reverse(orderedEntities);
if (schema.isLogEnabled()) {
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (this.logEnabled)");
methodBuilder.addStatement("$T.info(\"Update database '%s' from version %s to version %s\",this.name, previousVersion, currentVersion)", Logger.class);
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
}
methodBuilder.addComment("if we have a list of update task, try to execute them");
methodBuilder.beginControlFlow("if (options.updateTasks != null)");
methodBuilder.addStatement("$T<$T> tasks = buildTaskList(previousVersion, currentVersion)", List.class, SQLiteUpdateTask.class);
methodBuilder.beginControlFlow("for ($T task : tasks)", SQLiteUpdateTask.class);
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (this.logEnabled)");
methodBuilder.addStatement("$T.info(\"Begin update database from version %s to %s\", previousVersion, previousVersion+1)", Logger.class);
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
methodBuilder.addStatement("task.execute(database, previousVersion, previousVersion+1)");
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (this.logEnabled)");
methodBuilder.addStatement("$T.info(\"End update database from version %s to %s\", previousVersion, previousVersion+1)", Logger.class);
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
methodBuilder.addStatement("previousVersion++");
methodBuilder.endControlFlow();
methodBuilder.nextControlFlow("else");
methodBuilder.addComment("drop all tables");
methodBuilder.addStatement("$T.dropTablesAndIndices(database)", SQLiteUpdateTaskHelper.class);
// reorder entities
Collections.reverse(orderedEntities);
methodBuilder.addCode("\n");
methodBuilder.addCode("// generate tables\n");
for (SQLiteEntity item : orderedEntities) {
if (schema.isLogEnabled()) {
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (this.logEnabled)");
methodBuilder.addCode("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL);\n", Logger.class, BindTableGenerator.tableClassName(null, item));
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
}
methodBuilder.addCode("database.execSQL($T.CREATE_TABLE_SQL);\n", BindTableGenerator.tableClassName(null, item));
}
// use generated entities too
for (GeneratedTypeElement item : schema.generatedEntities) {
if (schema.isLogEnabled()) {
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (this.logEnabled)");
methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class, TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
}
methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)", TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
}
methodBuilder.endControlFlow();
methodBuilder.beginControlFlow("if (options.databaseLifecycleHandler != null)");
methodBuilder.addStatement("options.databaseLifecycleHandler.onUpdate(database, previousVersion, currentVersion, true)");
methodBuilder.endControlFlow();
classBuilder.addMethod(methodBuilder.build());
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity 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);
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity 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);
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity 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");
}
}
Aggregations