0

As of now i just want to check whether the order of the clauses - select, from, where, order by. are correct in a query. I tried this:

String pattern1 = "select";
String pattern2 =  "from";
String pattern3 = "(where\\s*(.*?)|order by\\s*(.*?)|where\\s*(.*?)order by\\s*(.*?))";
String pattern4 = "(;|$)";
Pattern p = Pattern.compile(pattern1 + "(.*?)" + pattern2 + "(.*?)" + pattern3 + pattern4);

But still this matches an incorrect query like this:

select * from student order by marks where id<8;

I need to do it manually without using any external libraries.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
Avinash S
  • 31
  • 1
  • 6

1 Answers1

1

SQL allows arbitrary naming of columns, so simple string searches are not going to be sufficient. Although not recommended, you can write a query such as this:

select 1 as `order`, 2 as `select`, 3 as `limit`

That is, simple string searches are not sufficient.

And, even worse, SQL supports subqueries. The following is a reasonable example:

select (select col
        from t
        where . . .
        group by x
        order by count(*) desc
        limit 1
       ) col, . . .
from tt
order by 2;

In other words, it is a recursive grammar.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786