I am trying to generate random columns with the use of below method and after generating columns, I am using those columns in my SELECT sql
.
final String columnsList = getColumns(table.getColumns());
final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, " + columnsList + " from " + table.getTableName() + " where id = ?";
/**
* A simple method to get the column names in the order in which it was
* inserted
*
* @param columns
* @return
*/
private String getColumns(final List<String> columns) {
List<String> copy = new ArrayList<String>(columns);
Collections.shuffle(copy);
int rNumber = random.nextInt(columns.size());
List<String> subList = copy.subList(0, rNumber);
Collections.sort(subList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return columns.indexOf(o1) < columns.indexOf(o2) ? -1 : 1;
}
});
return StringUtils.join(subList, ",");
}
Problem Statement:-
Sometimes I have seen is columnsList
value is empty and if it is empty then selectSql
will not work as there will be extra ,
before from keyword
. How can I make sure getColumns
should return atleast one entry everytime.
I believe nextInt
will generate random number between 0 (inclusively) and n (exclusively)
. So it might be possible that it will pick 0 sometimes, Any way to generate random number between 1(inclusively) and n (exclusively)
One way is:
return subList.isEmpty() ? "1" : StringUtils.join(subList, ",");
But I think better is to modify selectSql
to
final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE " + columnsList + " from " + table.getTableName() + " where id = ?";
And then
return subList.isEmpty() ? "" : ","+StringUtils.join(subList, ",");
If you want at leas one value from random you can also use this:
int rNumber = 1+random.nextInt(columns.size()-1);