use of com.abubusoft.kripton.processor.sqlite.model.SQLProperty in project kripton by xcesco.
the class JQLChecker method extractProjections.
/**
* Retrieve set of projected field.
*
* @param jql
* @return
*/
public Set<JQLProjection> extractProjections(final JQLContext jqlContext, String jqlValue, final Finder<SQLProperty> entity) {
final Set<JQLProjection> result = new LinkedHashSet<JQLProjection>();
final One<Boolean> projection = new One<Boolean>(null);
analyzeInternal(jqlContext, jqlValue, new JqlBaseListener() {
@Override
public void enterProjected_columns(Projected_columnsContext ctx) {
if (projection.value0 == null) {
projection.value0 = true;
}
}
@Override
public void exitProjected_columns(Projected_columnsContext ctx) {
projection.value0 = false;
}
@Override
public void enterResult_column(Result_columnContext ctx) {
if (projection.value0 != true)
return;
ProjectionBuilder builder = ProjectionBuilder.create();
if (ctx.getText().endsWith("*")) {
builder.type(ProjectionType.STAR);
} else if (ctx.table_name() != null) {
builder.table(ctx.expr().table_name().getText());
} else if (ctx.expr().column_fully_qualified_name() != null && ctx.expr().column_fully_qualified_name().column_simple_name() != null) {
if (ctx.expr().column_fully_qualified_name().table_simple_name() != null) {
builder.table(ctx.expr().column_fully_qualified_name().table_simple_name().getText());
}
String jqlColumnName = ctx.expr().column_fully_qualified_name().column_simple_name().getText();
builder.column(jqlColumnName);
builder.property(entity.findPropertyByName(jqlColumnName));
builder.type(ProjectionType.COLUMN);
} else {
builder.type(ProjectionType.COMPLEX);
builder.expression(ctx.expr().getText());
}
if (ctx.column_alias() != null) {
builder.alias(ctx.column_alias().getText());
}
result.add(builder.build());
}
@Override
public void exitResult_column(Result_columnContext ctx) {
}
});
if (result.size() == 1 && result.toArray(new JQLProjection[1])[0].type == ProjectionType.STAR) {
// the projected columns are full
result.clear();
if (entity != null) {
for (SQLProperty item : entity.getCollection()) {
JQLProjection col = new JQLProjection(ProjectionType.COLUMN, entity.getSimpleName(), item.getName(), null, null, item);
result.add(col);
}
}
}
return result;
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLProperty in project kripton by xcesco.
the class SelectBeanListenerHelper 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();
// LiteralType listenerType = LiteralType.of(OnReadBeanListener.class, entity.getElement());
ParameterizedTypeName listenerType = ParameterizedTypeName.get(ClassName.get(OnReadBeanListener.class), TypeName.get(entity.getElement().asType()));
// List<SQLProperty> fields = fieldList.value1;
TypeName entityClass = typeName(entity.getElement());
int counter = SqlBuilderHelper.countParameterOfType(method, listenerType);
if (counter == 0) {
// non listener found
throw (new InvalidMethodSignException(method, "there is no parameter of type \"ReadCursorListener\""));
}
if (counter > 1) {
// more than one listener found
throw (new InvalidMethodSignException(method, "there are more than one parameter of type \"ReadCursorListener\""));
}
String listenerName = SqlSelectBuilder.getNameParameterOfType(method, listenerType);
methodBuilder.addCode("$T resultBean=new $T();", entityClass, entityClass);
methodBuilder.addCode("\n");
// methodBuilder.beginControlFlow("try");
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.addCode("int rowCount=_cursor.getCount();\n");
methodBuilder.beginControlFlow("do\n");
// reset mapping
methodBuilder.addCode("// reset mapping\n");
{
int i = 0;
for (SQLProperty item : entity.getCollection()) {
if (item.isNullable()) {
SQLTransformer.resetBean(methodBuilder, entityClass, "resultBean", item, "_cursor", "index" + i + "");
methodBuilder.addCode(";");
methodBuilder.addCode("\n");
} else {
methodBuilder.addCode("// " + item.getName() + " does not need reset\n");
}
i++;
}
}
methodBuilder.addCode("\n");
// generate mapping
methodBuilder.addCode("// generate mapping\n");
{
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("$L.onRead(resultBean, _cursor.getPosition(), rowCount);\n", listenerName);
methodBuilder.endControlFlow("while (_cursor.moveToNext())");
// close try { open cursor
methodBuilder.endControlFlow();
// close method
methodBuilder.endControlFlow();
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLProperty in project kripton by xcesco.
the class SqlBuilderHelper method generateJavaDocForContentProvider.
/**
* @param method
* @param methodBuilder
*/
public static void generateJavaDocForContentProvider(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
// javadoc
String operation = method.jql.operationType.toString();
methodBuilder.addJavadoc("<h1>Content provider URI ($L operation):</h1>\n", operation);
methodBuilder.addJavadoc("<pre>$L</pre>\n\n", method.contentProviderUriTemplate.replace("*", "[*]"));
methodBuilder.addJavadoc("<h2>JQL $L for Content Provider</h2>\n", operation);
methodBuilder.addJavadoc("<pre>$L</pre>\n\n", method.jql.value);
methodBuilder.addJavadoc("<h2>SQL $L for Content Provider</h2>\n", operation);
String sql = JQLChecker.getInstance().replace(method, method.jql, new com.abubusoft.kripton.processor.sqlite.grammars.jql.JQLReplacerListenerImpl(method) {
@Override
public String onColumnName(String columnName) {
SQLProperty tempProperty = currentEntity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
return tempProperty.columnName;
}
});
methodBuilder.addJavadoc("<pre>$L</pre>\n\n", sql);
if (method.contentProviderUriVariables.size() > 0) {
methodBuilder.addJavadoc("<h3>Path variables defined:</h3>\n<ul>\n");
for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
methodBuilder.addJavadoc("<li><strong>$${$L}</strong> at path segment $L</li>\n", variable.value, variable.pathSegmentIndex);
}
methodBuilder.addJavadoc("</ul>\n\n");
}
if (!method.hasDynamicWhereConditions()) {
methodBuilder.addJavadoc("<p><strong>Dynamic where statement is ignored, due no param with @$L was added.</strong></p>\n\n", BindSqlDynamicWhere.class.getSimpleName());
}
methodBuilder.addJavadoc("<p><strong>In URI, * is replaced with [*] for javadoc rapresentation</strong></p>\n\n");
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLProperty in project kripton by xcesco.
the class SqlModifyBuilder method generateModifierForContentProvider.
/**
* <p>
* Generate update and delete used in content provider class.
* </p>
*
* @param elementUtils
* @param builder
* @param method
* @param updateResultType
*/
private static void generateModifierForContentProvider(Elements elementUtils, Builder builder, final SQLiteModelMethod method, ModifyType updateResultType) {
final SQLiteDaoDefinition daoDefinition = method.getParent();
final SQLiteEntity entity = daoDefinition.getEntity();
final Set<String> columns = new LinkedHashSet<>();
JQLChecker jqlChecker = JQLChecker.getInstance();
// parameters extracted from query
final One<String> whereStatement = new One<>();
if (method.jql.isWhereConditions()) {
// parameters extracted from query
final One<Boolean> alreadyFoundWhereStatement = new One<>(false);
// put in whereStatement value of where statement.
jqlChecker.replaceVariableStatements(method, method.jql.value, new JQLReplaceVariableStatementListenerImpl() {
@Override
public String onWhere(String statement) {
if (alreadyFoundWhereStatement.value0 == false) {
whereStatement.value0 = statement;
alreadyFoundWhereStatement.value0 = true;
return "";
} else {
// DO NOTHING
return null;
}
}
});
}
List<JQLPlaceHolder> placeHolders = jqlChecker.extractFromVariableStatement(method, whereStatement.value0);
// remove placeholder for dynamic where, we are not interested here
placeHolders = SqlBuilderHelper.removeDynamicPlaceHolder(placeHolders);
checkContentProviderVarsAndArguments(method, placeHolders);
// detect column used for content value
jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public String onColumnNameToUpdate(String columnName) {
SQLProperty tempProperty = entity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
columns.add(tempProperty.columnName);
return null;
}
});
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.contentProviderMethodName);
// params
methodBuilder.addParameter(ParameterSpec.builder(Uri.class, "uri").build());
if (updateResultType == ModifyType.UPDATE_BEAN || updateResultType == ModifyType.UPDATE_RAW) {
methodBuilder.addParameter(ParameterSpec.builder(ContentValues.class, "contentValues").build());
}
methodBuilder.addParameter(ParameterSpec.builder(String.class, "selection").build());
methodBuilder.addParameter(ParameterSpec.builder(ArrayTypeName.of(String.class), "selectionArgs").build());
methodBuilder.returns(Integer.TYPE);
// retrieve content values
if (updateResultType == ModifyType.UPDATE_BEAN || updateResultType == ModifyType.UPDATE_RAW) {
methodBuilder.addStatement("$T _contentValues=contentValuesForContentProvider(contentValues)", KriptonContentValues.class);
} else {
methodBuilder.addStatement("$T _contentValues=contentValues()", KriptonContentValues.class);
}
SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);
// query builder
methodBuilder.addStatement("$T _sqlBuilder=sqlBuilder()", StringBuilder.class);
generateInitForDynamicWhereVariables(method, methodBuilder, "selection", "selectionArgs");
SqlBuilderHelper.generateWhereCondition(methodBuilder, method, false);
int i = 0;
// every controls was done in constructor of SQLiteModelMethod
for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
AssertKripton.assertTrue(SqlBuilderHelper.validate(variable.value, placeHolders, i), "In '%s.%s' content provider URI path variables and variables in where conditions are different. If SQL uses parameters, they must be defined in URI path.", daoDefinition.getName(), method.getName());
JQLParameterName paramName = JQLParameterName.parse(variable.value);
SQLProperty entityProperty = entity.get(paramName.getValue());
if (entityProperty != null) {
methodBuilder.addCode("// Add parameter $L at path segment $L\n", variable.value, variable.pathSegmentIndex);
// methodBuilder.addStatement("_sqlWhereParams.add(uri.getPathSegments().get($L))",
// variable.pathSegmentIndex);
methodBuilder.addStatement("_contentValues.addWhereArgs(uri.getPathSegments().get($L))", variable.pathSegmentIndex);
AssertKripton.assertTrue(TypeUtility.isTypeIncludedIn(entityProperty.getPropertyType().getTypeName(), String.class, Long.class, Long.TYPE), "In '%s.%s' content provider URI path variables %s must be String of Long type", daoDefinition.getName(), method.getName(), entityProperty.getName());
}
i++;
}
if (method.hasDynamicWhereConditions() && method.hasDynamicWhereArgs()) {
// ASSERT: only with dynamic where conditions
methodBuilder.beginControlFlow("if ($T.hasText(_sqlDynamicWhere) && _sqlDynamicWhereArgs!=null)", StringUtils.class);
if (method.hasDynamicWhereConditions()) {
methodBuilder.beginControlFlow("for (String _arg: _sqlDynamicWhereArgs)");
// methodBuilder.addStatement("_sqlWhereParams.add(_arg)");
methodBuilder.addStatement("_contentValues.addWhereArgs(_arg)");
methodBuilder.endControlFlow();
}
methodBuilder.endControlFlow();
}
// column checj
switch(updateResultType) {
case UPDATE_BEAN:
case UPDATE_RAW:
SqlBuilderHelper.generateColumnCheckSet(builder, method, columns);
SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.values().keySet()", true, null);
break;
default:
break;
}
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (_context.isLogEnabled())");
generateLogForModifiers(method, methodBuilder);
if (method.jql.operationType == JQLType.UPDATE) {
// generate log for content values
SqlBuilderHelper.generateLogForContentValues(method, methodBuilder);
}
// log for where parames
SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
methodBuilder.addCode("\n// execute SQL\n");
switch(updateResultType) {
case DELETE_BEAN:
case DELETE_RAW:
methodBuilder.addStatement("int result = database().delete($S, _sqlWhereStatement, _contentValues.whereArgsAsArray())", daoDefinition.getEntity().getTableName());
if (method.getParent().getParent().generateRx) {
GenericSQLHelper.generateSubjectNext(methodBuilder, SubjectType.DELETE);
}
break;
case UPDATE_BEAN:
case UPDATE_RAW:
if (method.jql.conflictAlgorithmType == ConflictAlgorithmType.NONE) {
methodBuilder.addStatement("int result = database().update($S, _contentValues.values(), _sqlWhereStatement, _contentValues.whereArgsAsArray())", daoDefinition.getEntity().getTableName());
} else {
methodBuilder.addCode("// conflict algorithm $L\n", method.jql.conflictAlgorithmType);
methodBuilder.addStatement("int result = database().updateWithOnConflict($S, _contentValues.values(), _sqlWhereStatement, _contentValues.whereArgsAsArray()), $L)", daoDefinition.getEntity().getTableName(), method.jql.conflictAlgorithmType.getConflictAlgorithm());
}
if (method.getParent().getParent().generateRx) {
GenericSQLHelper.generateSubjectNext(methodBuilder, SubjectType.UPDATE);
}
break;
}
// support for livedata
if (daoDefinition.hasLiveData()) {
methodBuilder.addComment("support for livedata");
methodBuilder.addStatement(BindDaoBuilder.METHOD_NAME_REGISTRY_EVENT + "(result)");
}
methodBuilder.addStatement("return result");
// 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("*", "[*]"));
switch(updateResultType) {
case UPDATE_BEAN:
case UPDATE_RAW:
methodBuilder.addJavadoc("@param contentValues content values\n");
break;
default:
break;
}
methodBuilder.addJavadoc("@param selection dynamic part of <code>where</code> statement $L\n", method.hasDynamicWhereConditions() ? "" : "<b>NOT USED</b>");
methodBuilder.addJavadoc("@param selectionArgs arguments of dynamic part of <code>where</code> statement $L\n", method.hasDynamicWhereConditions() ? "" : "<b>NOT USED</b>");
methodBuilder.addJavadoc("@return number of effected rows\n");
builder.addMethod(methodBuilder.build());
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLProperty in project kripton by xcesco.
the class BindM2MBuilder method generateEntity.
/**
* @param entity
* @return
* @throws IOException
*/
private void generateEntity(M2MEntity entity) throws IOException {
if (!entity.needToCreate)
return;
String tableName = entity.tableName;
String entityClassName = entity.name;
AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDaoMany2Many.class, entity.getPackageName(), entityClassName);
// @formatter:off
classBuilder = TypeSpec.classBuilder(entityClassName).addModifiers(Modifier.PUBLIC).addAnnotation(AnnotationSpec.builder(BindTable.class).addMember("name", "$S", tableName).build());
// @formatter:on
// javadoc for class
classBuilder.addJavadoc("<p>");
classBuilder.addJavadoc("\nGenerated entity implementation for <code>$L</code>\n", entity.name);
classBuilder.addJavadoc("</p>\n");
JavadocUtility.generateJavadocGeneratedBy(classBuilder);
// classBuilder.addJavadoc(" @see $T\n",
// TypeUtility.className(entity.getElement().getQualifiedName().toString()));
{
// @formatter:off
FieldSpec fieldSpec = FieldSpec.builder(Long.TYPE, entity.idName, Modifier.PUBLIC).addJavadoc("Primary key\n").addAnnotation(AnnotationSpec.builder(BindColumn.class).addMember("columnType", "$T.$L", ColumnType.class, ColumnType.PRIMARY_KEY).build()).build();
// @formatter:on
classBuilder.addField(fieldSpec);
}
Converter<String, String> converterFK = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);
Converter<String, String> converterFieldName = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
Converter<String, String> converterField2ColumnName = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.LOWER_UNDERSCORE);
String fkPrefix = converterFK.convert(entity.idName);
String fk1Name = converterField2ColumnName.convert(entity.entity1Name.simpleName() + fkPrefix);
String fk2Name = converterField2ColumnName.convert(entity.entity2Name.simpleName() + fkPrefix);
String field1Name = converterFieldName.convert(entity.entity1Name.simpleName() + fkPrefix);
String field2Name = converterFieldName.convert(entity.entity2Name.simpleName() + fkPrefix);
{
// @formatter:off
FieldSpec fieldSpec = FieldSpec.builder(Long.TYPE, field1Name, Modifier.PUBLIC).addJavadoc("Foreign key to $T model class\n", entity.entity1Name).addAnnotation(AnnotationSpec.builder(BindColumn.class).addMember("foreignKey", "$T.class", entity.entity1Name).addMember("onDelete", "$T.$L", ForeignKeyAction.class, ForeignKeyAction.CASCADE).build()).build();
// @formatter:on
classBuilder.addField(fieldSpec);
}
{
// @formatter:off
FieldSpec fieldSpec = FieldSpec.builder(Long.TYPE, field2Name, Modifier.PUBLIC).addJavadoc("Foreign key to $T model class\n", entity.entity2Name).addAnnotation(AnnotationSpec.builder(BindColumn.class).addMember("foreignKey", "$T.class", entity.entity2Name).addMember("onDelete", "$T.$L", ForeignKeyAction.class, ForeignKeyAction.CASCADE).build()).build();
// @formatter:on
classBuilder.addField(fieldSpec);
}
TypeSpec typeSpec = classBuilder.build();
JavaWriterHelper.writeJava2File(filer, entity.getPackageName(), typeSpec);
List<SQLProperty> properties = new ArrayList<SQLProperty>();
{
SQLProperty property = new SQLProperty(entity.idName, entity.getClassName());
property.columnType = ColumnType.PRIMARY_KEY;
property.columnName = entity.idName;
property.setNullable(false);
property.setPrimaryKey(true);
property.foreignClassName = null;
properties.add(property);
}
{
SQLProperty property = new SQLProperty(field1Name, entity.getClassName());
property.columnType = ColumnType.INDEXED;
property.columnName = fk1Name;
property.setNullable(false);
property.setPrimaryKey(false);
property.onDeleteAction = ForeignKeyAction.CASCADE;
property.foreignClassName = entity.entity1Name.toString();
properties.add(property);
}
{
SQLProperty property = new SQLProperty(field2Name, entity.getClassName());
property.columnType = ColumnType.INDEXED;
property.columnName = fk2Name;
property.setNullable(false);
property.setPrimaryKey(false);
property.onDeleteAction = ForeignKeyAction.CASCADE;
property.foreignClassName = entity.entity2Name.toString();
properties.add(property);
}
GeneratedTypeElement entityElement = new GeneratedTypeElement(entity.getPackageName(), classBuilder.build(), tableName, fk1Name + ", " + fk2Name);
entityElement.properties = properties;
entityResult.add(entityElement);
}
Aggregations