17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 1: Basic <strong>Defensive</strong> <strong>Database</strong> <strong>Programming</strong> Techniques@SubjectBeginning='Ne';SubjectBody------------------------------ -------------------Next release delayedStill fixing bugsNew printer arrivedBy the kitchen area-- must return nothingEXEC dbo.SelectMessagesBySubjectBeginning@SubjectBeginning='No Such Subject';SubjectBody------------------------------ -------------------Listing 1-2: A few simple tests against the provided test data demonstrate thatresults match expectations.Handling special characters in searchingIn defensive database programming, it is essential to construct cases of unintended usewith which to break our code. The test data in Listing 1-1 and the stored procedure callsin Listing 1-2 demonstrate the cases of intended use, and clearly the procedure works,when it is used as intended.However, have we considered all the possible cases? Will the procedure continue to workas expected in cases of unintended use? Can we find any hidden bugs in this procedure?In fact, it is embarrassingly easy to break this stored procedure, simply by adding a few"off-topic" messages to our table, as shown in Listing 1-3.INSERT INTO dbo.Messages( Subject ,Body)SELECT '[OT] Great vacation in Norway!' ,'Pictures already uploaded'UNION ALLSELECT '[OT] Great new camera' ,24

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!