use of com.abubusoft.kripton.processor.sqlite.model.SQLProperty in project kripton by xcesco.
the class SqlInsertBuilder method generateInsertForContentProvider.
/**
* <p>
* Generate insert used in content provider class.
* </p>
*
* @param methodBuilder
* @param method
* @param insertResultType
*/
private static void generateInsertForContentProvider(TypeSpec.Builder classBuilder, final SQLiteModelMethod method, InsertType insertResultType) {
final SQLiteDaoDefinition daoDefinition = method.getParent();
final SQLiteEntity entity = daoDefinition.getEntity();
final Set<String> columns = new LinkedHashSet<>();
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.contentProviderMethodName);
ParameterSpec parameterSpec;
parameterSpec = ParameterSpec.builder(Uri.class, "uri").build();
methodBuilder.addParameter(parameterSpec);
parameterSpec = ParameterSpec.builder(ContentValues.class, "contentValues").build();
methodBuilder.addParameter(parameterSpec);
methodBuilder.returns(Long.TYPE);
SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);
// just detect which columns are admitted
JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public String onColumnName(String columnName) {
SQLProperty tempProperty = entity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
columns.add(tempProperty.columnName);
return tempProperty.columnName;
}
@Override
public String onColumnFullyQualifiedName(String tableName, String columnName) {
AssertKripton.fail("Inconsistent state");
return null;
}
});
// generate columnCheckSet
SqlBuilderHelper.generateColumnCheckSet(classBuilder, method, columns);
// retrieve content values
methodBuilder.addStatement("$T _contentValues=contentValuesForContentProvider(contentValues)", KriptonContentValues.class);
// generate column check
SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.values().keySet()", true, null);
methodBuilder.addCode("\n");
// every controls was done in constructor of SQLiteModelMethod
for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
SQLProperty entityProperty = entity.get(variable.value);
if (entityProperty != null) {
methodBuilder.addCode("// Add parameter $L at path segment $L\n", variable.value, variable.pathSegmentIndex);
TypeName entityPropertyType = entityProperty.getPropertyType().getTypeName();
if (TypeUtility.isString(entityPropertyType)) {
methodBuilder.addStatement("contentValues.put($S, uri.getPathSegments().get($L))", entityProperty.columnName, variable.pathSegmentIndex);
} else {
methodBuilder.addStatement("contentValues.put($S, Long.valueOf(uri.getPathSegments().get($L)))", entityProperty.columnName, variable.pathSegmentIndex);
}
}
}
// generate log for inser operation
SqlBuilderHelper.generateLogForContentValuesContentProvider(method, methodBuilder);
ConflictAlgorithmType conflictAlgorithmType = InsertBeanHelper.getConflictAlgorithmType(method);
String conflictString1 = "";
String conflictString2 = "";
if (conflictAlgorithmType != ConflictAlgorithmType.NONE) {
conflictString1 = "WithOnConflict";
conflictString2 = ", " + conflictAlgorithmType.getConflictAlgorithm();
methodBuilder.addCode("// conflict algorithm $L\n", method.jql.conflictAlgorithmType);
}
methodBuilder.addComment("insert operation");
methodBuilder.addStatement("long result = database().insert$L($S, null, _contentValues.values()$L)", conflictString1, daoDefinition.getEntity().getTableName(), conflictString2);
if (method.getParent().getParent().generateRx) {
GenericSQLHelper.generateSubjectNext(methodBuilder, SubjectType.INSERT);
}
// support for livedata
if (daoDefinition.hasLiveData()) {
methodBuilder.addComment("support for livedata");
methodBuilder.addStatement(BindDaoBuilder.METHOD_NAME_REGISTRY_EVENT + "(result>0?1:0)");
}
methodBuilder.addStatement("return result");
// javadoc
// we add at last javadoc, because need info is built at last.
SqlBuilderHelper.generateJavaDocForContentProvider(method, methodBuilder);
methodBuilder.addJavadoc("@param uri $S\n", method.contentProviderUriTemplate.replace("*", "[*]"));
methodBuilder.addJavadoc("@param contentValues content values\n");
methodBuilder.addJavadoc("@return new row's id\n");
classBuilder.addMethod(methodBuilder.build());
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLProperty 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.SQLProperty 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.SQLProperty 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.SQLProperty in project kripton by xcesco.
the class CodeBuilderUtility method generateContentValuesFromEntity.
public static void generateContentValuesFromEntity(Elements elementUtils, SQLiteModelMethod method, Class<? extends Annotation> annotationClazz, Builder methodBuilder, List<String> alreadyUsedBeanPropertiesNames) {
// all check is already done
SQLiteEntity entity = method.getParent().getEntity();
String entityName = method.getParameters().get(0).value0;
TypeName entityClassName = typeName(entity.getElement());
AssertKripton.assertTrueOrInvalidMethodSignException(!method.hasAdapterForParam(entityName), method, "method's parameter '%s' can not use a type adapter", entityName);
Set<String> updateColumns = JQLChecker.getInstance().extractColumnsToInsertOrUpdate(method, method.jql.value, entity);
SQLProperty item;
for (String columnName : updateColumns) {
item = entity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(item != null, method, columnName);
// add property to list of used properties
if (method.isLogEnabled()) {
methodBuilder.addCode("_contentValues.put($S, ", item.columnName);
} else {
methodBuilder.addCode("_contentValues.put(");
}
SQLTransformer.javaProperty2ContentValues(methodBuilder, entityClassName, entityName, item);
methodBuilder.addCode(");\n");
// if (TypeUtility.isNullable(item) && !item.hasTypeAdapter()) {
// methodBuilder.nextControlFlow("else");
//
// if (method.isLogEnabled()) {
// methodBuilder.addCode("_contentValues.putNull($S);\n", item.columnName);
// } else {
// methodBuilder.addCode("_contentValues.putNull();\n");
// }
//
//
// methodBuilder.endControlFlow();
// }
}
methodBuilder.addCode("\n");
}
Aggregations