Получаем параметры из интерфейса:
final String currency - если NULL или пусто, или ALL означает все валюты, кроме той, которую выбрал пользователь. Список не нужен, где
final Boolean isSFlag - если null, то это не будет частью where else, если столбец имеет значение true или flase;
Означает, что если валюта равна нулю, а isSFlag равна нулю, тогда оператор select будет:
select col1, col2 from 'collecitonA'
если валюта 'INR', то
select col1, col2 from 'collecitonA' where currenncy = 'INR'
Если 'INRI и флаг ложны, то:
select col1, col2 from 'collecitonA' where currenncy = 'INR' and flagS = false
Каков хороший способ построить этот выбор? Что имею до сих пор:
/** Create statement per params
* ignore currency if null or ALL.
* ignore isSFlag if null */
private Statement crt(final String currency, final Boolean isSFlag) {
Statement statement = null;
try {
System.out.println("Cur :\"" + currency + "\", isSh " + isSFlag);
Expression whr = createWhere(currency, isSFlag);
//FromPath pp = select(path(i("c1"), "*"))
// .from(i("MutalFundData"));//.as("S") .where(whr);//can I add the where clause only if its non empty ?
Expression slct = path(i("c1", "c2"));
final String frm = "MutualFundData";
if(whr == null){
statement = select(slct).from(i(frm));
}else{
statement = select(slct).from(i(frm)).where(whr);
}
System.out.println(statement);
} catch (Exception e) {
System.out.println("err " + e + ", isSh " + isSFlag);
}
return statement;
}
private Expression createWhere(final String currency, final Boolean isSFlag) {
String currencyUpper = currency == null ? null : currency.toUpperCase();
Expression where = x("1=1");//can i initialize this to some sort of empty expression o
// Use apache fn for checking if empty
//if its all or empty string ignore it - dont add to where clause
if (currency != null && currency.length() > 0 && (!currency.equals("ALL"))) {
where = where.and(x("CURRENCY")).eq(i(currencyUpper));
}
//for SFlag need 3 value from front end - whether all rows, or only where SFlag false or where true, use NULL or an int/ String to denote
if (isSFlag != null) {
where = where.and("isSFlag").eq(isSFlag);
}
return where;
}
//not yet using.
private Expression createWhere2(final String currency, final Boolean isSFlag) {
String currencyUpper = currency == null ? null : currency.toUpperCase();
Expression where = null;//can i initialize this to some sort of empty expression o
// Use apache fn for checking if empty
//if its all or empty string ignore it - dont add to where clause
if (currency != null && currency.length() > 0 && (!currency.equals("ALL"))) {
//where = chckAnd(where, x("CURRENCY")).eq(i(currencyUpper));
where = x("CURRENCY").eq(i(currencyUpper);
}
//for SFlag need 3 value from front end - whether all rows, or only where SFlag false or where true, use NULL or an int/ String to denote
if (isSFlag != null) {
where = chckAnd(where, x("isSFlag").eq(isSFlag));
}
return where;
}
private Expression chckAnd(Expression a, Expression b){
if(a == null)return b;
return a.and(b);
}
Это возвращает
Cur :, isSh null SELECT
c1
.* FROMMutalFundData
WHERE 1=1Cur :USD, isSh null ВЫБЕРИТЕ
c1
.* ОТMutalFundData
, ГДЕ 1=1 И ВАЛЮТА =USD
Cur :USD, isSh true SELECT
c1
.* FROMMutalFundData
WHERE 1=1 AND CURRENCY =USD
AND isSFlag = TRUE
Любой способ:
- добавить куда только при необходимости
- инициализировать где, но оставить его пустым и не писать И, если не требуется? Нужен флаг инициализирован? здесь используется функция chck. А что, если первым логическим оператором было ИЛИ? нужен еще один помощник. Можно ли улучшить библиотеку Couchbase?