use of com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext in project kripton by xcesco.
the class ModifyRawHelper method generateJavaDoc.
/**
* @param daoDefinition
* @param method
* @param methodBuilder
* @param updateMode
* @param whereCondition
* @param where
* @param methodParams
* @param updateableParams
*
* @return sql generated
*/
private void generateJavaDoc(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder, boolean updateMode, String whereCondition, Pair<String, List<Pair<String, TypeName>>> where, List<Pair<String, TypeName>> methodParams) {
final List<SQLProperty> updatedProperties = new ArrayList<>();
final One<Boolean> onWhereStatement = new One<Boolean>(false);
String sqlModify = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public void onWhereStatementBegin(Where_stmtContext ctx) {
onWhereStatement.value0 = true;
}
@Override
public void onWhereStatementEnd(Where_stmtContext ctx) {
onWhereStatement.value0 = false;
}
@Override
public String onColumnNameToUpdate(String columnName) {
SQLProperty tempProperty = currentEntity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
updatedProperties.add(tempProperty);
return tempProperty.columnName;
}
@Override
public String onColumnName(String columnName) {
SQLProperty tempProperty = currentEntity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
return tempProperty.columnName;
}
@Override
public String onBindParameter(String bindParameterName) {
String resolvedParamName = method.findParameterNameByAlias(bindParameterName);
AssertKripton.assertTrueOrUnknownParamInJQLException(resolvedParamName != null, method, bindParameterName);
if (onWhereStatement.value0) {
return "${" + bindParameterName + "}";
} else {
return ":" + bindParameterName;
}
}
});
if (updateMode) {
methodBuilder.addJavadoc("<h2>SQL update</h2>\n");
methodBuilder.addJavadoc("<pre>$L</pre>\n", sqlModify);
methodBuilder.addJavadoc("\n");
// list of updated fields
methodBuilder.addJavadoc("<h2>Updated columns:</h2>\n");
methodBuilder.addJavadoc("<ul>\n");
for (SQLProperty property : updatedProperties) {
methodBuilder.addJavadoc("\t<li>$L</li>\n", property.columnName);
// methodBuilder.addJavadoc("<dd>is binded to query's parameter
// <strong>$L</strong> and method's parameter
// <strong>$L</strong></dd>\n", "${" + resolvedName + "}",
// property.value0);
}
methodBuilder.addJavadoc("</ul>");
methodBuilder.addJavadoc("\n\n");
} else {
methodBuilder.addJavadoc("<h2>SQL delete</h2>\n");
methodBuilder.addJavadoc("<pre>$L</pre>\n", sqlModify);
methodBuilder.addJavadoc("\n\n");
}
// list of where parameter
methodBuilder.addJavadoc("<h2>Where parameters:</h2>\n");
methodBuilder.addJavadoc("<dl>\n");
for (Pair<String, TypeName> property : where.value1) {
String rawName = method.findParameterNameByAlias(property.value0);
methodBuilder.addJavadoc("\t<dt>$L</dt>", "${" + property.value0 + "}");
methodBuilder.addJavadoc("<dd>is mapped to method's parameter <strong>$L</strong></dd>\n", rawName);
}
methodBuilder.addJavadoc("</dl>");
methodBuilder.addJavadoc("\n\n");
if (method.hasDynamicWhereConditions()) {
methodBuilder.addJavadoc("<dl>\n");
methodBuilder.addJavadoc("<dt>$L</dt><dd>is part of where conditions resolved at runtime. In above SQL it is displayed as #{$L}</dd>", method.dynamicWhereParameterName, JQLDynamicStatementType.DYNAMIC_WHERE);
methodBuilder.addJavadoc("\n</dl>");
methodBuilder.addJavadoc("\n\n");
}
// dynamic conditions
if (method.hasDynamicWhereConditions()) {
methodBuilder.addJavadoc("<h2>Method's parameters and associated dynamic parts:</h2>\n");
methodBuilder.addJavadoc("<dl>\n");
if (method.hasDynamicWhereConditions()) {
methodBuilder.addJavadoc("<dt>$L</dt><dd>is part of where conditions resolved at runtime. In above SQL it is displayed as #{$L}</dd>", method.dynamicWhereParameterName, JQLDynamicStatementType.DYNAMIC_WHERE);
}
methodBuilder.addJavadoc("</dl>");
methodBuilder.addJavadoc("\n\n");
}
// method parameters
if (methodParams.size() > 0) {
for (Pair<String, TypeName> param : methodParams) {
String resolvedName = method.findParameterAliasByName(param.value0);
methodBuilder.addJavadoc("@param $L", param.value0);
if (method.isThisDynamicWhereConditionsName(param.value0)) {
methodBuilder.addJavadoc("\n\tis used as dynamic where conditions\n");
} else if (where.value1.contains(new Pair<>(resolvedName, param.value1))) {
methodBuilder.addJavadoc("\n\tis used as where parameter <strong>$L</strong>\n", "${" + resolvedName + "}");
} else {
methodBuilder.addJavadoc("\n\tis used as updated field <strong>$L</strong>\n", resolvedName);
}
}
}
// if true, field must be associate to ben attributes
TypeName returnType = method.getReturnClass();
// define return value
if (returnType == TypeName.VOID) {
} else {
methodBuilder.addJavadoc("\n");
if (isIn(returnType, Boolean.TYPE, Boolean.class)) {
if (updateMode) {
methodBuilder.addJavadoc("@return <code>true</code> if record is updated, <code>false</code> otherwise");
} else {
methodBuilder.addJavadoc("@return <code>true</code> if record is deleted, <code>false</code> otherwise");
}
// methodBuilder.addCode("return result!=0;\n");
} else if (isIn(returnType, Long.TYPE, Long.class, Integer.TYPE, Integer.class, Short.TYPE, Short.class)) {
if (updateMode) {
methodBuilder.addJavadoc("@return number of updated records");
} else {
methodBuilder.addJavadoc("@return number of deleted records");
}
// methodBuilder.addCode("return result;\n");
} else {
// more than one listener found
throw (new InvalidMethodSignException(method, "invalid return type"));
}
methodBuilder.addJavadoc("\n");
}
}
use of com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext in project kripton by xcesco.
the class SqlModifyBuilder method generateLogForModifiers.
/**
* generate sql log
*
* @param method
* @param methodBuilder
* @param schema
* @param entity
* @param jqlChecker
*/
public static void generateLogForModifiers(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
JQLChecker jqlChecker = JQLChecker.getInstance();
final One<Boolean> usedInWhere = new One<Boolean>(false);
methodBuilder.addCode("\n// display log\n");
String sqlForLog = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public String onColumnNameToUpdate(String columnName) {
// only entity's columns
return currentEntity.findPropertyByName(columnName).columnName;
}
@Override
public String onColumnName(String columnName) {
// return entity.findByName(columnName).columnName;
return currentSchema.findColumnNameByPropertyName(method, columnName);
}
@Override
public String onBindParameter(String bindParameterName) {
if (usedInWhere.value0) {
return "?";
} else {
String paramName = bindParameterName;
if (paramName.contains(".")) {
String[] a = paramName.split("\\.");
if (a.length == 2) {
paramName = a[1];
}
}
SQLProperty property = currentEntity.findPropertyByName(paramName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(property != null, method, bindParameterName);
return ":" + property.columnName;
}
}
@Override
public void onWhereStatementBegin(Where_stmtContext ctx) {
usedInWhere.value0 = true;
}
@Override
public void onWhereStatementEnd(Where_stmtContext ctx) {
usedInWhere.value0 = false;
}
});
if (method.jql.dynamicReplace.containsKey(JQLDynamicStatementType.DYNAMIC_WHERE)) {
methodBuilder.addStatement("$T.info($S, $L)", Logger.class, sqlForLog.replace(method.jql.dynamicReplace.get(JQLDynamicStatementType.DYNAMIC_WHERE), "%s"), "StringUtils.ifNotEmptyAppend(_sqlDynamicWhere,\" AND \")");
} else {
methodBuilder.addStatement("$T.info($S)", Logger.class, sqlForLog);
}
}
use of com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext in project kripton by xcesco.
the class JQLBuilder method buildJQLUpdate.
/**
* <pre>
* UPDATE bean01 SET text=${text} WHERE id=${id}
* </pre>
*
* @param method
* @param preparedJql
* @return
*/
private static JQL buildJQLUpdate(final SQLiteModelMethod method, final JQL result, Map<JQLDynamicStatementType, String> dynamicReplace, String preparedJql) {
final Class<? extends Annotation> annotation = BindSqlUpdate.class;
if (StringUtils.hasText(preparedJql)) {
result.value = preparedJql;
// UPDATE can contains bind parameter in column values and select
// statement
final One<Boolean> inWhereCondition = new One<Boolean>(false);
final One<Boolean> inColumnsToUpdate = new One<Boolean>(false);
JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {
@Override
public void enterProjected_columns(Projected_columnsContext ctx) {
if (inColumnsToUpdate.value0) {
result.containsSelectOperation = true;
}
}
@Override
public void enterConflict_algorithm(Conflict_algorithmContext ctx) {
result.conflictAlgorithmType = ConflictAlgorithmType.valueOf(ctx.getText().toUpperCase());
}
@Override
public void enterWhere_stmt(Where_stmtContext ctx) {
inWhereCondition.value0 = true;
}
@Override
public void exitWhere_stmt_clauses(Where_stmt_clausesContext ctx) {
inWhereCondition.value0 = false;
}
@Override
public void enterBind_parameter(Bind_parameterContext ctx) {
if (inWhereCondition.value0) {
result.bindParameterOnWhereStatementCounter++;
} else {
result.bindParameterAsColumnValueCounter++;
}
}
@Override
public void enterColumns_to_update(Columns_to_updateContext ctx) {
inColumnsToUpdate.value0 = true;
}
@Override
public void exitColumns_to_update(Columns_to_updateContext ctx) {
inColumnsToUpdate.value0 = false;
}
});
JQLChecker.getInstance().replaceVariableStatements(method, preparedJql, new JQLReplaceVariableStatementListenerImpl() {
@Override
public String onWhere(String statement) {
result.annotatedWhere = true;
result.staticWhereConditions = true;
return null;
}
});
if (result.containsSelectOperation) {
AssertKripton.assertTrueOrInvalidMethodSignException(method.getReturnClass().equals(TypeName.VOID), method, "defined JQL requires that method's return type is void");
}
} else {
final SQLiteDaoDefinition dao = method.getParent();
Set<String> fields;
ModifyType modifyType = SqlModifyBuilder.detectModifyType(method, JQLType.UPDATE);
if (modifyType == ModifyType.UPDATE_BEAN) {
fields = extractFieldsFromAnnotation(method, annotation, false);
} else {
fields = extractFieldsFromMethodParameters(method, annotation);
}
AssertKripton.assertTrueOrInvalidMethodSignException(fields.size() > 0, method, "no field was specified for update");
result.conflictAlgorithmType = ConflictAlgorithmType.valueOf(AnnotationUtility.extractAsEnumerationValue(method.getElement(), annotation, AnnotationAttributeType.CONFLICT_ALGORITHM_TYPE));
StringBuilder builder = new StringBuilder();
builder.append(UPDATE_KEYWORD);
builder.append(" " + result.conflictAlgorithmType.getSqlForInsert());
// entity name
builder.append(dao.getEntitySimplyClassName());
// recreate fields
final One<String> prefix = new One<>("");
if (result.hasParamBean()) {
prefix.value0 = result.paramBean + ".";
}
builder.append(" " + SET_KEYWORD + " ");
builder.append(forEachFields(fields, new OnFieldListener() {
@Override
public String onField(String item) {
return item + "=${" + prefix.value0 + item + "}";
}
}));
builder.append(defineWhereStatement(method, result, annotation, dynamicReplace));
result.value = builder.toString();
}
result.operationType = JQLType.UPDATE;
result.dynamicReplace = dynamicReplace;
return result;
}
use of com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext in project kripton by xcesco.
the class JQLBuilder method buildJQLInsert.
/**
* <pre>
*
* INSERT INTO person (name, surname, birth_city, birth_day) VALUES (${name}, ${surname}, ${birthCity}, ${birthDay})
* </pre>
*
* @param method
* @param preparedJql
* @return
*/
private static JQL buildJQLInsert(SQLiteModelMethod method, final JQL result, String preparedJql) {
if (StringUtils.hasText(preparedJql)) {
result.value = preparedJql;
// INSERT can contains bind parameter in column values and select
// statement
final One<Boolean> inColumnValueSet = new One<Boolean>(false);
final One<Boolean> inWhereStatement = new One<Boolean>(false);
JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {
@Override
public void enterConflict_algorithm(Conflict_algorithmContext ctx) {
result.conflictAlgorithmType = ConflictAlgorithmType.valueOf(ctx.getText().toUpperCase());
}
@Override
public void enterProjected_columns(Projected_columnsContext ctx) {
result.containsSelectOperation = true;
}
@Override
public void enterWhere_stmt(Where_stmtContext ctx) {
inWhereStatement.value0 = true;
}
@Override
public void exitWhere_stmt(Where_stmtContext ctx) {
inWhereStatement.value0 = false;
}
@Override
public void enterColumn_value_set(Column_value_setContext ctx) {
inColumnValueSet.value0 = true;
}
@Override
public void exitColumn_value_set(Column_value_setContext ctx) {
inColumnValueSet.value0 = false;
}
@Override
public void enterBind_parameter(Bind_parameterContext ctx) {
if (inWhereStatement.value0) {
result.bindParameterOnWhereStatementCounter++;
} else if (inColumnValueSet.value0) {
result.bindParameterAsColumnValueCounter++;
}
AssertKripton.assertTrue(inWhereStatement.value0 || inColumnValueSet.value0, "unknown situation!");
}
});
if (result.containsSelectOperation) {
AssertKripton.assertTrueOrInvalidMethodSignException(method.getReturnClass().equals(TypeName.VOID), method, "defined JQL requires that method's return type is void");
}
// ASSERT: a INSERT-SELECT SQL can not contains parameters on values
// section.
} else {
// use annotation's attribute value and exclude and bean definition
// to
final Class<? extends Annotation> annotation = BindSqlInsert.class;
final SQLiteDaoDefinition dao = method.getParent();
final boolean includePrimaryKey = AnnotationUtility.extractAsBoolean(method.getElement(), annotation, AnnotationAttributeType.INCLUDE_PRIMARY_KEY);
// define field list
// every method parameter can be used only as insert field
InsertType insertResultType = SqlInsertBuilder.detectInsertType(method);
Set<String> fields;
if (insertResultType == InsertType.INSERT_BEAN) {
fields = extractFieldsFromAnnotation(method, annotation, includePrimaryKey);
} else {
fields = extractFieldsFromMethodParameters(method, annotation);
}
result.conflictAlgorithmType = ConflictAlgorithmType.valueOf(AnnotationUtility.extractAsEnumerationValue(method.getElement(), annotation, AnnotationAttributeType.CONFLICT_ALGORITHM_TYPE));
StringBuilder builder = new StringBuilder();
builder.append(INSERT_KEYWORD);
builder.append(" " + result.conflictAlgorithmType.getSqlForInsert());
builder.append(INTO_KEYWORD);
builder.append(" " + dao.getEntitySimplyClassName());
builder.append(" (");
builder.append(forEachFields(fields, new OnFieldListener() {
@Override
public String onField(String item) {
return item;
}
}));
builder.append(") ");
builder.append(VALUES_KEYWORD);
final One<String> prefix = new One<>("");
if (result.hasParamBean()) {
prefix.value0 = result.paramBean + ".";
}
builder.append(" (");
builder.append(forEachFields(fields, new OnFieldListener() {
@Override
public String onField(String item) {
return "${" + prefix.value0 + item + "}";
}
}));
builder.append(")");
result.value = builder.toString();
}
result.operationType = JQLType.INSERT;
result.dynamicReplace = new HashMap<>();
return result;
}
use of com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Where_stmtContext in project kripton by xcesco.
the class JQLChecker method replaceVariableStatements.
/**
* <p>
* Given a sql, replace som component like where, order by, etc..
*
* <p>
* Note that only first level of variable statements will be replaced.
*
* @param jql
* @param listener
* @return
*/
public String replaceVariableStatements(final JQLContext jqlContext, final String jql, final JQLReplaceVariableStatementListener listener) {
final List<Triple<Token, Token, String>> replace = new ArrayList<>();
final One<Integer> currentSelectLevel = new One<Integer>(-1);
JqlBaseListener rewriterListener = new JqlBaseListener() {
@Override
public void enterSelect_core(Select_coreContext ctx) {
currentSelectLevel.value0++;
}
@Override
public void enterSelect_or_values(Select_or_valuesContext ctx) {
currentSelectLevel.value0++;
}
@Override
public void exitSelect_core(Select_coreContext ctx) {
currentSelectLevel.value0--;
}
@Override
public void exitSelect_or_values(Select_or_valuesContext ctx) {
currentSelectLevel.value0--;
}
@Override
public void enterProjected_columns(Projected_columnsContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onProjectedColumns(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
@Override
public void enterWhere_stmt(Where_stmtContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onWhere(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
@Override
public void enterOrder_stmt(Order_stmtContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onOrderBy(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
@Override
public void enterGroup_stmt(Group_stmtContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onGroup(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
@Override
public void enterHaving_stmt(Having_stmtContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onHaving(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
@Override
public void enterOffset_stmt(Offset_stmtContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onOffset(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
@Override
public void enterLimit_stmt(Limit_stmtContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onLimit(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
@Override
public void enterColumn_name_set(Column_name_setContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 2;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onColumnNameSet(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
@Override
public void enterColumn_value_set(Column_value_setContext ctx) {
// we work on level 0
if (currentSelectLevel.value0 > 0)
return;
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 2;
if (start == stop)
return;
String statement = jql.substring(start, stop);
String value = listener.onColumnValueSet(statement);
if (value != null) {
replace.add(new Triple<Token, Token, String>(ctx.start, ctx.stop, value));
}
}
};
return replaceInternal(jqlContext, jql, replace, rewriterListener);
}
Aggregations