Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate or constrain direct SQL input from user?

I am going to provide SQL console like data.stackexchange.com for developers on one of the sites I have. The problem is I can not let them execute all type of SQL. So there will be some constrains. Here are some example constrains

  • No query can contain COUNT() function
  • Every query must contain LIMIT with maximum value 100
  • Number of column can not be more than 5
  • Some tables' data will not be accessible due to privacy region.
  • Only SELECT statements will be allowed to be used.

What I am doing right now?

I using regular expression to filter these. Also planning to invoke EXPLAIN or similar query to determine its impact in db prior to executing.

Is there any better way than regex? How it's done on data.SE? Is there anything else I should be worried about?

Update 1

These two rules can be applied by restricting user permission in database server.

  • Some tables' data will not be accessible due to privacy region.
  • Only SELECT statements will be allowed to be used.

So only problem is to validate the SQL

Update 2

I know If I write an SQL parser it'll do. It'll be like writing JS interpreter just remove eval() as its bad practice. So writing an SQL parser from scratch is really not an option. here.

like image 572
Shiplu Mokaddim Avatar asked Dec 26 '12 03:12

Shiplu Mokaddim


People also ask

How do you validate data in SQL?

To validate the sorting data from SQL we can use the order by clause. We can validate the data in sorting manner using order by clause. In Real life example if you want to sort the employee data according to alphabetical order then with using order by you can sort it using a single query.


1 Answers

You can create new grammar for yacc, that contains subset of SQL. Than you able to check input SQL with this grammar. SQL lex yacc grammar

like image 102
Kostia Shiian Avatar answered Nov 14 '22 20:11

Kostia Shiian