use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity in project kripton by xcesco.
the class SqlInsertBuilder method detectInsertType.
public static InsertType detectInsertType(SQLiteModelMethod method) {
SQLiteDaoDefinition daoDefinition = method.getParent();
SQLiteEntity entity = daoDefinition.getEntity();
InsertType insertResultType = null;
// check type of arguments
int count = 0;
for (Pair<String, TypeName> param : method.getParameters()) {
if (TypeUtility.isEquals(param.value1, typeName(entity.getElement()))) {
count++;
}
}
AssertKripton.failWithInvalidMethodSignException(method.getParameters().size() == 0, method, " INSERT operations require at least one parameter");
if (count == 0) {
// method to insert raw data: no bean is used
insertResultType = InsertType.INSERT_RAW;
ModelAnnotation annotation = method.getAnnotation(BindSqlInsert.class);
// check value attribute
AssertKripton.failWithInvalidMethodSignException(AnnotationUtility.extractAsStringArray(method, annotation, AnnotationAttributeType.FIELDS).size() > 0, method, " can not use attribute %s in this kind of query definition", AnnotationAttributeType.FIELDS.getValue());
// check excludeFields attribute
AssertKripton.failWithInvalidMethodSignException(AnnotationUtility.extractAsStringArray(method, annotation, AnnotationAttributeType.EXCLUDED_FIELDS).size() > 0, method, " can not use attribute %s in this kind of query definition", AnnotationAttributeType.EXCLUDED_FIELDS.getValue());
// check if there is only one parameter
AssertKripton.failWithInvalidMethodSignException(method.getParameters().size() != 1 && TypeUtility.isEquals(method.getParameters().get(0).value1, daoDefinition.getEntityClassName()), method);
// check no
AssertKripton.failWithInvalidMethodSignException(annotation.getAttributeAsBoolean(AnnotationAttributeType.INCLUDE_PRIMARY_KEY), method, "attribute '%s' can not be used here", AnnotationAttributeType.INCLUDE_PRIMARY_KEY.getValue());
} else if (count == 1) {
insertResultType = InsertType.INSERT_BEAN;
AssertKripton.failWithInvalidMethodSignException(method.getParameters().size() > 1, method, " aspected only one parameter of %s type", daoDefinition.getEntityClassName());
} else {
throw (new InvalidMethodSignException(method, "only one parameter of type " + typeName(entity.getElement()) + " can be used"));
}
return insertResultType;
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity in project kripton by xcesco.
the class SqlSelectBuilder method generateSelect.
/**
* @param elementUtils
* @param builder
* @param method
* @throws ClassNotFoundException
*/
public static void generateSelect(Builder builder, SQLiteModelMethod method) throws ClassNotFoundException {
SQLiteDaoDefinition daoDefinition = method.getParent();
SQLiteEntity entity = daoDefinition.getEntity();
SelectBuilderUtility.SelectType selectResultType = null;
// if true, field must be associate to ben attributes
TypeName returnTypeName = method.getReturnClass();
ParameterizedTypeName readBeanListener = ParameterizedTypeName.get(ClassName.get(OnReadBeanListener.class), ClassName.get(entity.getElement()));
ClassName readCursorListener = ClassName.get(OnReadCursorListener.class);
ModelAnnotation annotation = method.getAnnotation(BindSqlSelect.class);
int pageSize = annotation.getAttributeAsInt(AnnotationAttributeType.PAGE_SIZE);
AssertKripton.failWithInvalidMethodSignException(pageSize < 0, method, "in @%s(pageSize) must be set with positive number", BindSqlSelect.class.getSimpleName());
AssertKripton.failWithInvalidMethodSignException(pageSize > 0 && method.hasDynamicPageSizeConditions(), method, "can not define @%s(pageSize) and mark a method parameter with @%s ", BindSqlSelect.class.getSimpleName(), BindSqlPageSize.class.getSimpleName());
if (TypeUtility.isTypeIncludedIn(returnTypeName, Void.class, Void.TYPE)) {
// return VOID (in the parameters must be a listener)
if (SqlBuilderHelper.hasParameterOfType(method, readCursorListener)) {
selectResultType = SelectBuilderUtility.SelectType.LISTENER_CURSOR;
} else if (SqlBuilderHelper.hasParameterOfType(method, readBeanListener)) {
selectResultType = SelectBuilderUtility.SelectType.LISTENER_BEAN;
}
} else if (TypeUtility.isTypeIncludedIn(returnTypeName, Cursor.class)) {
// return Cursor (no listener)
selectResultType = SelectBuilderUtility.SelectType.CURSOR;
} else if (returnTypeName instanceof ParameterizedTypeName) {
ParameterizedTypeName returnParameterizedTypeName = (ParameterizedTypeName) returnTypeName;
ClassName returnParameterizedClassName = returnParameterizedTypeName.rawType;
// return List (no listener)
AssertKripton.assertTrueOrInvalidMethodSignException(returnParameterizedTypeName.typeArguments.size() == 1, method, "return type %s is not supported", returnTypeName);
TypeName elementName = returnParameterizedTypeName.typeArguments.get(0);
Class<?> wrapperClazz = Class.forName(returnParameterizedClassName.toString());
if (PaginatedResult.class.isAssignableFrom(wrapperClazz)) {
// method must have pageSize, statically or dynamically
// defined
AssertKripton.assertTrueOrInvalidMethodSignException(method.hasDynamicPageSizeConditions() || pageSize > 0, method, "use of PaginatedResult requires 'pageSize' attribute or a @%s annotated parameter", returnTypeName, BindSqlPageSize.class.getSimpleName());
// paged result
AssertKripton.assertTrueOrInvalidMethodSignException(TypeUtility.isEquals(elementName, entity.getName().toString()), method, "return type %s is not supported", returnTypeName);
selectResultType = SelectBuilderUtility.SelectType.PAGED_RESULT;
// set typeName of paginatedResult
method.paginatedResultName = "paginatedResult";
} else if (Collection.class.isAssignableFrom(wrapperClazz)) {
if (TypeUtility.isEquals(elementName, entity.getName().toString())) {
// entity list
selectResultType = SelectBuilderUtility.SelectType.LIST_BEAN;
} else if (SQLTransformer.isSupportedJDKType(elementName) || TypeUtility.isByteArray(elementName)) {
// scalar list
selectResultType = SelectBuilderUtility.SelectType.LIST_SCALAR;
} else {
AssertKripton.failWithInvalidMethodSignException(true, method, "%s is invalid return type", method.getReturnClass());
}
}
} else if (TypeUtility.isEquals(returnTypeName, entity)) {
// return one element (no listener)
selectResultType = SelectBuilderUtility.SelectType.BEAN;
} else if (SQLTransformer.isSupportedJDKType(returnTypeName) || TypeUtility.isByteArray(returnTypeName)) {
// return single value string, int, long, short, double, float,
// String (no listener)
selectResultType = SelectBuilderUtility.SelectType.SCALAR;
}
AssertKripton.assertTrueOrInvalidMethodSignException(selectResultType != null, method, "'%s' as return type is not supported", returnTypeName);
// generate select method
selectResultType.generate(builder, method);
if (method.hasLiveData()) {
// generate
selectResultType.generateLiveData(builder, method);
}
if (method.contentProviderEntryPathEnabled) {
// we need to generate UPDATE or DELETE for content provider to
generateSelectForContentProvider(builder, method, selectResultType);
}
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteEntity 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.SQLiteEntity 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.SQLiteEntity 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();
}
Aggregations