Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if an sql query modifies the database

I have a list of strings that contain valid SQL expressions.
I need to execute only those that do not modify the database.
What would be the best way to do this? Just doing something like:

if(sqlQuery.contains("DELETE")){  
  //don't execute this
}

seems like a bad hack

Update:
I'll make this more specific.
I already have a list of SQL queries that are allowed. I want to make sure only these are executed.
What would be the best way to match against these?

like image 467
Jim Avatar asked Nov 02 '12 13:11

Jim


1 Answers

The easiest and best (most comprehensive) way to do this is to create a read-only user and only connect to the database with that user. In SQLServer, the easiest way to do this is to create the user and add them to the built-in "db_datareader" role. This will only allow SELECTs.

And you have to worry about more than just DELETEs, INSERTs or UPDATEs. You also have to be careful about calling any stored procedures, so to be safe you'd also want to remove execute rights, ALTER rights, GRANT rights, etc...

EDIT: Just execute this...

CREATE LOGIN [user] WITH PASSWORD='password', DEFAULT_DATABASE=[your_db], CHECK_POLICY=OFF
GO
CREATE USER [user] FOR LOGIN [user]
EXEC sp_addrolemember N'db_datareader', N'your_db'
GO
like image 145
Matt Brock Avatar answered Oct 16 '22 19:10

Matt Brock