I was not very clear: one of the functions receives text of query to be executed. Function must construct "counting" query for the same conditions. It is not known what kind of query will be passed. Ideally, function must be able to handle ANY type of query like:
from Employee emp
select emp from Employee emp
select distinct emp from Employee emp
emp from Employee emp
These queries require slightly different methods of building COUNT(*) queries...
It seems I have solved my problem because I wrote that function. But I clearly understand, this function sucks. There are tons of queries this function will not be able to handle. But it works for most of my queries...
Code:
static Pattern pattern = null;
static
{
Perl5Compiler compiler = new Perl5Compiler();
try
{
pattern = compiler.compile("^ \\s* (select)? (.*?) (from .*) $",
Perl5Compiler.EXTENDED_MASK | Perl5Compiler.READ_ONLY_MASK | Perl5Compiler.CASE_INSENSITIVE_MASK);
}
catch (MalformedPatternException exception)
{
throw new RuntimeException("Can'not initialize - pattern can not be compiled");
}
}
public static String buildCountingQuery(String originalQuery)
{
// >> from Employee emp
// << SELECT COUNT(*) from Employee emp
// >> select emp from Employee emp
// << SELECT COUNT(emp) from Employee emp
// >> select distinct emp from Employee emp
// << SELECT COUNT(DISTINCT emp) from Employee emp
// >> emp from Employee emp
// << SELECT COUNT(emp) from Employee emp
String countWhat = "*";
String queryTail = null;
PatternMatcher matcher = new Perl5Matcher();
MatchResult match;
if (matcher.contains(originalQuery, pattern))
{
match = matcher.getMatch();
String selectTokens = match.group(2);
if (selectTokens != null)
{
selectTokens = selectTokens.trim();
if (selectTokens.length() > 0)
countWhat = selectTokens;
}
queryTail = match.group(3);
}
else
queryTail = originalQuery;
return "SELECT COUNT(" + countWhat + ") " + queryTail;
}