/*
(non-Javadoc)

@see com.abubusoft.kripton.processor.sqlite.SQLiteSelectBuilder.
SelectCodeGenerator#generate(com.squareup.javapoet.MethodSpec.Builder)
167792
@Override
	public void generateSpecializedPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) {
		TypeName returnTypeName = method.getReturnClass();

		//ASSERT: returnType is a supported type
		
		// no column or too many columns
		AssertKripton.assertTrueOrInvalidMethodSignException(fieldList.size() == 1, method, "no way to understand which field is the result for this method");				

		SQLTransform t = SQLTransformer.lookup(returnTypeName);

		methodBuilder.addCode("$T result=", returnTypeName);
		t.generateDefaultValue(methodBuilder);
		methodBuilder.addCode(";\n");

		methodBuilder.addCode("\n");
		// methodBuilder.beginControlFlow("try");
		methodBuilder.beginControlFlow("if (_cursor.moveToFirst())");

		// generate index from columns
		methodBuilder.addCode("\n");

		if (TypeUtility.isNullable(returnTypeName)) {
			methodBuilder.addCode("if (_cursor.isNull(0)) { return null; }\n");
		} else {
			methodBuilder.addCode("if (_cursor.isNull(0)) { return ");
			t.generateDefaultValue(methodBuilder);
			methodBuilder.addCode("; }\n", t);
		}
		methodBuilder.addCode("result=");
		t.generateReadValueFromCursor(methodBuilder, method.getParent(), returnTypeName, "_cursor", "0");
		methodBuilder.addCode(";\n");

		// end cursor
		methodBuilder.endControlFlow();

		methodBuilder.addCode("return result;\n");
		// end method
		methodBuilder.endControlFlow();
	}
22555
private TypeSpec generateBuilder( RestService restService ) {

        TypeSpec.Builder typeBuilder = TypeSpec.classBuilder( restService.getBuilderSimpleClassName() )
                .addModifiers( Modifier.PUBLIC, Modifier.FINAL )
                .addJavadoc( "Generated REST service builder for {@link $L}.\n", restService.getTypeElement().getQualifiedName() )
                .addMethod( MethodSpec.constructorBuilder().addModifiers( Modifier.PRIVATE ).build() );

        Map<TypeMirror, MethodSpec> mapperGetters = buildMappers( typeBuilder, restService );

        for ( RestServiceMethod method : restService.getMethods() ) {
            buildMethod( typeBuilder, mapperGetters, method );
        }

        return typeBuilder.build();
    }
1364767
protected void _generate(SarlClass clazz, IExtraLanguageGeneratorContext context) {
		final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(clazz);
		final PyAppendable appendable = createAppendable(jvmType, context);
		if (generateTypeDeclaration(
				this.qualifiedNameProvider.getFullyQualifiedName(clazz).toString(),
				clazz.getName(), clazz.isAbstract(),
				getSuperTypes(clazz.getExtends(), clazz.getImplements()),
				getTypeBuilder().getDocumentation(clazz),
				true,
				clazz.getMembers(), appendable, context, null)) {
			final QualifiedName name = getQualifiedNameProvider().getFullyQualifiedName(clazz);
			writeFile(name, appendable, context);
		}
	}
101562
public static void generate(ConfigurationImpl configuration,
                                IndexBuilder indexbuilder) {
        SplitIndexWriter indexgen;
        DocPath filename = DocPath.empty;
        DocPath path = DocPaths.INDEX_FILES;
        try {
            Set<Object> keys = new TreeSet<>(Arrays.asList(indexbuilder.elements()));
            keys.addAll(configuration.tagSearchIndexKeys);
            List<Object> elements = new ArrayList<>(keys);
            ListIterator<Object> li = elements.listIterator();
            while (li.hasNext()) {
                Object ch = li.next();
                filename = DocPaths.indexN(li.nextIndex());
                indexgen = new SplitIndexWriter(configuration,
                        path.resolve(filename),
                        indexbuilder, elements, li.previousIndex(), li.nextIndex());
                indexgen.generateIndexFile((Character) ch);
                if (!li.hasNext()) {
                    indexgen.createSearchIndexFiles();
                }
                indexgen.close();
            }
        } catch (IOException exc) {
            configuration.standardmessage.error(
                        "doclet.exception_encountered",
                        exc.toString(), filename.getPath());
            throw new DocletAbortException(exc);
        }
    }
390726
private static void generateSelectForContentProvider(Builder builder, final SQLiteModelMethod method, SelectType selectResultType) {
		final SQLiteDaoDefinition daoDefinition = method.getParent();
		final SQLiteEntity entity = method.getEntity();
		final Set<String> columns = new LinkedHashSet<>();

		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.contentProviderMethodName);
		if (!method.getParent().hasSamePackageOfSchema()) {
			methodBuilder.addModifiers(Modifier.PUBLIC);
		}

		// params
		methodBuilder.addParameter(ParameterSpec.builder(Uri.class, "uri").build());
		methodBuilder.addParameter(ParameterSpec.builder(ArrayTypeName.of(String.class), "projection").build());
		methodBuilder.addParameter(ParameterSpec.builder(String.class, "selection").build());
		methodBuilder.addParameter(ParameterSpec.builder(ArrayTypeName.of(String.class), "selectionArgs").build());
		methodBuilder.addParameter(ParameterSpec.builder(String.class, "sortOrder").build());

		methodBuilder.returns(Cursor.class);

		SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);

		JQLChecker jqlChecker = JQLChecker.getInstance();
		SplittedSql splittedSql = generateSQL(method, methodBuilder, true);

		List<JQLPlaceHolder> placeHolders = jqlChecker.extractFromVariableStatement(method, splittedSql.sqlWhereStatement);
		// remove placeholder for dynamic where, we are not interested here
		placeHolders = SqlBuilderHelper.removeDynamicPlaceHolder(placeHolders);
		AssertKripton.assertTrue(placeHolders.size() == method.contentProviderUriVariables.size(),
				"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());

		Set<JQLProjection> projectedColumns = jqlChecker.extractProjections(method, method.jql.value, entity);
		for (JQLProjection item : projectedColumns) {
			if (item.type == ProjectionType.COLUMN) {
				if (item.alias != null) {
					columns.add(entity.get(item.alias.trim()).columnName);
				} else {
					columns.add(entity.get(item.column.trim()).columnName);
				}
			} else {
				columns.add(item.expression.trim());
			}
		}

		methodBuilder.addStatement("$T _contentValues=contentValues()", KriptonContentValues.class);
		methodBuilder.addStatement("$T _sqlBuilder=sqlBuilder()", StringBuilder.class);
		SqlModifyBuilder.generateInitForDynamicWhereVariables(method, methodBuilder, "selection", "selectionArgs");

		methodBuilder.addStatement("$T _projectionBuffer=new $T()", StringBuilder.class, StringBuilder.class);
		if (method.jql.isOrderBy()) {
			methodBuilder.addStatement("String _sortOrder=sortOrder");
		}

		methodBuilder.addStatement("_sqlBuilder.append($S)", splittedSql.sqlBasic);

		SqlBuilderHelper.generateWhereCondition(methodBuilder, method, false);

		generateDynamicPartOfQuery(method, methodBuilder, splittedSql, false);

		// generate and check columns
		{
			methodBuilder.addCode("\n// manage projected columns\n");
			methodBuilder.addStatement("String _columnSeparator=\"\"");
			methodBuilder.beginControlFlow("if (projection!=null && projection.length>0)");
			// generate projected column check
			String columnCheckSetName = SqlBuilderHelper.generateColumnCheckSet(builder, method, columns);
			SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "projection", true, new OnColumnListener() {

				@Override
				public void onColumnCheck(MethodSpec.Builder methodBuilder, String projectedColumnVariable) {
					methodBuilder.addStatement("_projectionBuffer.append(_columnSeparator + $L)", projectedColumnVariable);
					methodBuilder.addStatement("_columnSeparator=\", \"");
				}
			});
			methodBuilder.nextControlFlow("else");
			methodBuilder.beginControlFlow("for (String column: $L)", columnCheckSetName);
			methodBuilder.addStatement("_projectionBuffer.append(_columnSeparator + column)");
			methodBuilder.addStatement("_columnSeparator=\", \"");
			methodBuilder.endControlFlow();
			methodBuilder.endControlFlow();

			int i = 0;
			// extract pathVariables
			// 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 and where conditions must use same set of variables",
						daoDefinition.getName(), method.getName());

				SQLProperty entityProperty = entity.get(variable.value);
				TypeName methodParameterType = method.findParameterTypeByAliasOrName(variable.value);

				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);

				if (entityProperty != null) {

					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());
				} else if (methodParameterType != null) {
					AssertKripton.assertTrue(TypeUtility.isTypeIncludedIn(methodParameterType, 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(),
							method.findParameterNameByAlias(variable.value));
				}

				i++;
			}
		}

		// _sql must be always defined
		methodBuilder.addStatement("String _sql=String.format(_sqlBuilder.toString(), _projectionBuffer.toString())");
		SqlBuilderHelper.generateLogForSQL(method, methodBuilder);

		SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);

		methodBuilder.addCode("\n// execute query\n");
		// methodBuilder.addStatement("Cursor _result =
		// database().rawQuery(_sql, _sqlWhereParams.toArray(new
		// String[_sqlWhereParams.size()]))");
		methodBuilder.addStatement("Cursor _result = database().rawQuery(_sql, _contentValues.whereArgsAsArray())");

		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("*", "[*]"));
		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());
	}
1026580
protected void generateExpressionBuilderImpl() {
		final TypeReference builderInterface = getExpressionBuilderInterface();
		final TypeReference builder = getExpressionBuilderImpl();
		final StringConcatenationClient content = new StringConcatenationClient() {
			@Override
			protected void appendTo(TargetStringConcatenation it) {
				it.append("/** Builder of a " + getLanguageName() //$NON-NLS-1$
						+ " XExpression."); //$NON-NLS-1$
				it.newLine();
				it.append(" */"); //$NON-NLS-1$
				it.newLine();
				it.append("@SuppressWarnings(\"all\")"); //$NON-NLS-1$
				it.newLine();
				it.append("public class "); //$NON-NLS-1$
				it.append(builder.getSimpleName());
				it.append(" extends "); //$NON-NLS-1$
				it.append(getAbstractBuilderImpl());
				it.append(" implements "); //$NON-NLS-1$
				it.append(builderInterface);
				it.append(" {"); //$NON-NLS-1$
				it.newLineIfNotEmpty();
				it.newLine();
				it.append(generateMembers(false, false));
				it.append("}"); //$NON-NLS-1$
				it.newLineIfNotEmpty();
				it.newLine();
			}
		};
		final JavaFileAccess javaFile = getFileAccessFactory().createJavaFile(builder, content);
		javaFile.writeTo(getSrcGen());
	}
1308271
public static void generate(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws IOException {
		String className = schema.getName();

		String dataSourceName = PREFIX + className;

		className = className.replaceAll(BindDataSourceBuilder.SUFFIX, SUFFIX);
		className = PREFIX + className;

		PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
		String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, className);

		//@formatter:off
		builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT)
				.addTypeVariable(TypeVariableName.get("I"))
				.addTypeVariable(TypeVariableName.get("U"))
				.addTypeVariable(TypeVariableName.get("R"));
		//@formatter:on

		// javadoc
		builder.addJavadoc("\n<p>\nSpecialized async task to make async database operation on activity\n</p>\n");
		builder.addJavadoc("\n<p>\nUnlike standard async task, for an instance of this class can be used many time.\n</p>\n");
		builder.addJavadoc("\n<p>\nWhen method <code>execute</code> is invoked, an inner async task is created.\n</p>\n\n");
		JavadocUtility.generateJavadocGeneratedBy(builder);
		builder.addJavadoc("@param I input param\n");
		builder.addJavadoc("@param U update param\n");
		builder.addJavadoc("@param R result param\n\n");
		builder.addJavadoc("@see $T\n", className(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)));
		builder.addJavadoc("@see $T\n", className(dataSourceName));
		builder.addJavadoc("@see $T\n", BindAsyncTaskType.class);

		// build constructors
		builder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addStatement("this($T.READ)", BindAsyncTaskType.class)
				.addJavadoc("<p>\nWith this constructor, a read only database connection will be used\n</p>\n").build());

		builder.addMethod(
				MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addJavadoc("<p>\nWith this constructor it is possible to specify which type of database use in async task\n</p>\n\n")
						.addJavadoc("@param mode allows to specify if and how open a data source connection\n").addParameter(BindAsyncTaskType.class, "mode").addCode("this.mode = mode;").build());

		// define fields
		{
			FieldSpec.Builder fieldSpec = FieldSpec.builder(BindAsyncTaskType.class, "mode", Modifier.PROTECTED);
			fieldSpec.addJavadoc("Allows to specify how async task interacts with data source.\n\n");
			builder.addField(fieldSpec.build());
		}

		{
			ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.typeName("I"), TypeUtility.typeName("U"),
					TypeUtility.typeName("R"));
			FieldSpec.Builder fieldSpec = FieldSpec.builder(parameterizedTypeName, "asyncTask", Modifier.PROTECTED);
			fieldSpec.addJavadoc("Async task wrapped by this class\n\n");
			builder.addField(fieldSpec.build());
		}

		// build methods
		builder.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addJavadoc("Use this method for operations on UI-thread before start execution\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onExecute").returns(TypeUtility.typeName("R")).addParameter(TypeUtility.typeName(dataSourceName), "dataSource")
				.addJavadoc(
						"Method used to encapsulate operations on datasource\n\n@param dataSource\n\tuse it to retrieve DAO\n@return\n\tresult of operation (list, bean, etc) and execute transactions.\n")
				.addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT).addException(Throwable.class).build());
		builder.addMethod(MethodSpec.methodBuilder("onFinish").addParameter(TypeUtility.typeName("R"), "result").addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT)
				.addJavadoc("Use this method for operations on UI-thread after execution\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onProgressUpdate").addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.typeName("U")), "update").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
				.varargs().addJavadoc("Override this method to KRIPTON_DEBUG operation progress on UI-Thread\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onError").addParameter(Throwable.class, "exception").addModifiers(Modifier.PUBLIC)
				.addJavadoc("This method is invoked when <code>onExecute</code> method generate an exception.\n@param exception exception generated\n")
				.addStatement("$T.error(exception.getMessage())", Logger.class).addStatement("exception.printStackTrace()").build());

		// method execute1
		{
			MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("execute")
					.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
							.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
					.varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");

			executeBuilder.addStatement("executeOnExecutor($T.SERIAL_EXECUTOR, params)", android.os.AsyncTask.class);
			builder.addMethod(executeBuilder.build());
		}

		// method execute2
		{
			MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("executeOnExecutor").addParameter(Executor.class, "executor")
					.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
							.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
					.varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");

		//@formatter:off
		TypeSpec.Builder anonymous = TypeSpec.anonymousClassBuilder("")
				.addSuperinterface(ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.className("I"), TypeUtility.className("U"), TypeUtility.className("R")));
		anonymous.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addStatement("$L.this.onPreExecute()",className).build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("doInBackground").addModifiers(Modifier.PUBLIC).returns(TypeUtility.typeName("R")).addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
						.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value","$S", "unchecked").build())
						.build()).varargs(true)
				.addStatement("$L dataSource=$L.getInstance()", dataSourceName, dataSourceName)
				.addStatement("R result=null")
				.addStatement("boolean needToOpened=false")
				.addCode("if (mode==$T.READ) { needToOpened=true; dataSource.openReadOnlyDatabase(); } else if (mode==$T.READ_WRITE) { needToOpened=true; dataSource.openWritableDatabase();}\n", BindAsyncTaskType.class,BindAsyncTaskType.class)
				//.addStatement("$T sqlite=readOnlyTask ? dataSource.getReadableDatabase() : dataSource.getWritableDatabase()", SQLiteDatabase.class)
				.beginControlFlow("try")
				.addStatement("result=onExecute(dataSource)")
				.nextControlFlow("catch(Throwable e)")
					.addStatement("onError(e)")
				.nextControlFlow("finally")
					.beginControlFlow("if (needToOpened)")
					.addStatement("dataSource.close()")
					.endControlFlow()
				.endControlFlow()
				.addStatement("return result").build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("onProgressUpdate")
				.addModifiers(Modifier.PUBLIC)
				.addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("U"))
						, "values")
						.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value","$S", "unchecked").build())
						.build())
				.varargs(true)
				.addStatement("$L.this.onProgressUpdate(values)", className)
				.build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("onPostExecute")
				.addModifiers(Modifier.PUBLIC)
				.addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(TypeUtility.className("R"), "result").build())
				.addStatement("$L.this.onFinish(result)",className)
				.build());
		//@formatter:on

		//@formatter:off
		executeBuilder.addStatement("asyncTask=$L", anonymous.build());		
		executeBuilder.addStatement("asyncTask.executeOnExecutor(executor, params)", anonymous.build());
		builder.addMethod(executeBuilder.build());		
					
		anonymous.addMethod(MethodSpec.methodBuilder("cancel")
				.addModifiers(Modifier.PUBLIC)
				.addModifiers(Modifier.FINAL)
				.addParameter(Boolean.TYPE, "mayInterruptIfRunning")
				.beginControlFlow("if (asyncTask!=null, args)")
				.addStatement("return asyncTask.cancel(mayInterruptIfRunning)")
				.endControlFlow()
				.addStatement("return false").build());
		}

		
		// build SimpleAsyncTask
		builder.addType(TypeSpec.classBuilder("Simple")
				.addJavadoc("Simple implementation of async task. It uses read only database.\n\n")
				.addJavadoc("@see $T\n", TypeUtility.typeName(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)))
				.addJavadoc("@see $T\n", TypeUtility.typeName(dataSourceName))
				.addModifiers(Modifier.PUBLIC)
				.addModifiers(Modifier.STATIC)
				.addModifiers(Modifier.ABSTRACT)
				.addTypeVariable(TypeVariableName.get("R"))
				.superclass(
						ParameterizedTypeName.get(TypeUtility.className(className),
								TypeUtility.className("Void"), 
								TypeUtility.className("Void"), 
								TypeUtility.className("R")
								)							
				)				
				.addMethod(MethodSpec.constructorBuilder()
						.addModifiers(Modifier.PUBLIC)
						.addJavadoc("Create an simple async task allowing user to decide which kind of operation can be done on datasource")
						.addParameter(BindAsyncTaskType.class, "mode")
						.addStatement("super(mode)").build())
				.addMethod(MethodSpec.constructorBuilder()
						.addModifiers(Modifier.PUBLIC)
						.addJavadoc("Create an simple async task for data source read only operation")
						.addStatement("super($T.READ)", BindAsyncTaskType.class).build())
				.build());		
		//@formatter:on

		TypeSpec typeSpec = builder.build();
		JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);		
	}
17225
public static void generateSQLForInsertDynamic(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		methodBuilder.addComment("generate SQL for insert");
		JQLChecker checker = JQLChecker.getInstance();

		// replace the table name, other pieces will be removed
		String sql = checker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				return "?";
			}
		});

		final One<Integer> counter = new One<Integer>(0);
		sql = checker.replaceVariableStatements(method, sql, new JQLReplaceVariableStatementListenerImpl() {

			@Override
			public String onColumnNameSet(String statement) {
				counter.value0++;
				return "%s";
			}

			@Override
			public String onColumnValueSet(String statement) {
				counter.value0++;
				return "%s";
			}

		});

		if (counter.value0 == 2) {
			methodBuilder.addStatement("String _sql=String.format($S, _contentValues.keyList(), _contentValues.keyValueList())", sql);
		} else {
			methodBuilder.addStatement("String _sql=String.format($S, _contentValues.keyList())", sql);
		}
	}
171270
private static void generateSQLBuild(SQLiteModelMethod method, MethodSpec.Builder methodBuilder, SplittedSql splittedSql, boolean countQuery) {
		methodBuilder.addStatement("$T _sqlBuilder=sqlBuilder()", StringBuilder.class);
		methodBuilder.addStatement("_sqlBuilder.append($S)", splittedSql.sqlBasic.trim());

		SqlModifyBuilder.generateInitForDynamicWhereVariables(method, methodBuilder, method.dynamicWhereParameterName, method.dynamicWhereArgsParameterName);

		if (method.jql.isOrderBy()) {
			methodBuilder.addStatement("String _sortOrder=$L", method.jql.paramOrderBy);
		}

		SqlBuilderHelper.generateWhereCondition(methodBuilder, method, false);
		SqlSelectBuilder.generateDynamicPartOfQuery(method, methodBuilder, splittedSql, countQuery);
	}
642125
@Override
	public void generateSpecializedPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) {
		//ASSERT: returnType is a supported type
		
		// no column or too many columns
		AssertKripton.assertTrueOrInvalidMethodSignException(fieldList.size() == 1, method, "only one field can be defined as result for this method");				

		ParameterizedTypeName returnListName = (ParameterizedTypeName) method.getReturnClass();;

		TypeName collectionClass;
		ClassName listClazzName = returnListName.rawType;
		TypeName elementName = returnListName.typeArguments.get(0);

		collectionClass = SqlUtility.defineCollection(listClazzName);

		methodBuilder.addCode("\n");
		
		if (TypeUtility.isTypeEquals(collectionClass, TypeUtility.typeName(ArrayList.class))) {			
			methodBuilder.addStatement("$T<$T> resultList=new $T<$T>(_cursor.getCount())", collectionClass, elementName, collectionClass, elementName);
		} else {			
			methodBuilder.addStatement("$T<$T> resultList=new $T<$T>()", collectionClass, elementName, collectionClass, elementName);
		}
		methodBuilder.addCode("\n");
		
		SQLTransform t=SQLTransformer.lookup(returnListName);

		//@formatter:off
		methodBuilder.addCode("\n");
			methodBuilder.beginControlFlow("if (_cursor.moveToFirst())");
				methodBuilder.addCode("\n");
				methodBuilder.beginControlFlow("do\n");
					methodBuilder.beginControlFlow("if (!_cursor.isNull(0))");
						methodBuilder.addCode("resultList.add(");
						t.generateReadValueFromCursor(methodBuilder, method.getParent(), elementName, "_cursor", "0");
						methodBuilder.addCode(");\n");
					methodBuilder.nextControlFlow("else");
						methodBuilder.addCode("resultList.add(null);\n");		
					methodBuilder.endControlFlow();
				methodBuilder.endControlFlow("while (_cursor.moveToNext())");
			methodBuilder.endControlFlow();
			methodBuilder.addCode("return resultList;\n");
		methodBuilder.endControlFlow();
		//@formatter:on

	}
453014
private void generateBuilderClass() {
        if (data.isSkipBuilderGeneration()) {
            return;
        }
        List<PropertyGen> nonDerived = nonDerivedProperties();
        generateSeparator();
        String finalType = data.isTypeFinal() ? "final " : "";
        addLine(1, "/**");
        addLine(1, " * The bean-builder for {@code " + data.getTypeRaw() + "}.");
        if (data.isTypeGeneric()) {
            for (int j = 0; j < data.getTypeGenericCount(); j++) {
                addLine(1, " * @param " + data.getTypeGenericName(j, true) + "  the type");
            }
        }
        addLine(1, " */");
        String superBuilder;
        if (data.isSubClass()) {
            superBuilder = data.getSuperTypeRaw() + ".Builder" + data.getSuperTypeGeneric(true);
        } else if (data.isEffectiveBuilderScopeVisible()) {
            data.ensureImport(DirectFieldsBeanBuilder.class);
            superBuilder = "DirectFieldsBeanBuilder<" + data.getTypeNoExtends() + ">";
        } else {
            data.ensureImport(DirectPrivateBeanBuilder.class);
            superBuilder = "DirectPrivateBeanBuilder<" + data.getTypeNoExtends() + ">";
        }
        if (data.isConstructable()) {
            addLine(1, data.getEffectiveBuilderScope() + "static " + finalType +
                    "class Builder" + data.getTypeGeneric(true) + " extends " + superBuilder + " {");
        } else {
            addLine(1, data.getEffectiveBuilderScope() + "abstract static " + finalType +
                    "class Builder" + data.getTypeGeneric(true) + " extends " + superBuilder + " {");
        }
        if (nonDerived.size() > 0) {
            addBlankLine();
            generateBuilderProperties();
        }
        addBlankLine();
        generateBuilderConstructorNoArgs();
        generateBuilderConstructorCopy();
        generateIndentedSeparator();
        generateBuilderGet();
        generateBuilderSet();
        generateBuilderOtherSets();
        if (data.isConstructable()) {
            generateBuilderBuild();
        }
        generateIndentedSeparator();
        generateBuilderPropertySetMethods();
        generateIndentedSeparator();
        generateBuilderToString();
        addLine(1, "}");
        addBlankLine();
    }
904234
public static void generateSQLForStaticQuery(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		methodBuilder.addComment("generate static SQL for statement");
		JQLChecker checker = JQLChecker.getInstance();

		// replace the table name, other pieces will be removed
		String sql = checker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onColumnNameToUpdate(String columnName) {
				return onColumnName(columnName);
			}

			@Override
			public String onColumnName(String columnName) {
				SQLProperty tempProperty = method.getEntity().get(columnName);

				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				return "?";
			}
		});

		methodBuilder.addStatement("String _sql=$S", sql);
	}
674657
public static void generateSubjectNext(SQLiteEntity entity, MethodSpec.Builder methodBuilder,
			SubjectType subjectType, String value) {
		String subInsertType = "";
		if (subjectType == SubjectType.INSERT) {
			if (entity.getPrimaryKey().isType(String.class)) {
				subInsertType = "WithUid";
			} else {
				subInsertType = "WithId";
			}
		}

		methodBuilder.beginControlFlow("if (result>0)");
		methodBuilder.addComment("rx management ");
		methodBuilder.addStatement("subject.onNext($T.create$L$L($L))", SQLiteEvent.class, subjectType.value(),
				subInsertType, value);
		methodBuilder.endControlFlow();
	}
613653
@Override
	public void generate(TypeSpec.Builder classBuilder, boolean mapFields, SQLiteModelMethod method) {
		Set<JQLProjection> fieldList = JQLChecker.getInstance().extractProjections(method, method.jql.value, method.getEntity());

		// generate method code
		MethodSpec.Builder methodBuilder = generateMethodBuilder(method);

		generateCommonPart(method, classBuilder, methodBuilder, fieldList, true);
		methodBuilder.addComment("Specialized part - $L - BEGIN", this.getClass().getSimpleName());
		generateSpecializedPart(method, classBuilder, methodBuilder, fieldList, selectType.isMapFields());
		methodBuilder.addComment("Specialized part - $L - END", this.getClass().getSimpleName());

		if (!method.isPagedLiveData()) {
			// method ForLiveData do not have to be generated for paged live
			// data
			classBuilder.addMethod(methodBuilder.build());
		}

	}
468191
public SQLUnit generateSQL(final TableUnit tableUnit, final SQLBuilder sqlBuilder, final ShardingDataSourceMetaData shardingDataSourceMetaData) {
        return sqlBuilder.toSQL(tableUnit, getTableTokens(tableUnit), shardingRule, shardingDataSourceMetaData);
    }
1244418
public void generate() throws CodeGenerationException
    {
        for (AnnotationTypeDeclaration atd : _atds)
        {
            Collection<Declaration> decls = getAnnotationProcessorEnvironment().getDeclarationsAnnotatedWith(atd);
            for (Declaration decl : decls)
            {
                generate(decl);
            }
        }
    }
794798
@Override
   public Sql[] generateSql(final InsertStatement statement, final Database database,
         final SqlGeneratorChain sqlGeneratorChain) {
      for (final Entry<String, Object> entry : statement.getColumnValues().entrySet()) {
         entry.setValue(handleColumnValue(entry.getValue(), database));
      }
      return super.generateSql(statement, database, sqlGeneratorChain);
   }