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);
}
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"));
}
}
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();
}
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;
}
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);
}
}
}
}
Aggregations