Mirror

Abstraction of Runtime Queries from Code (Views: 14846)


Problem/Question/Abstract:

Programming methodology books such as 'The Pragmatic Programmer' by Andrew Hunt and David Thomas teach the principles of decoupling, abstraction and non-repetition. This article shows how to achieve some of these goals when codeing queries whose SQL statements are set at runtime.

Answer:

In article "Auxiliary TQuery used with queries built at run time", Fernando Martins suggested a way to avoid code replication when using TQuery objects with SQL statements set at runtime. Here I show how to take this a step further and remove the SQL from your code so that the queries can be changed without recompiling your program.

My queries are stored within an inifile in the program's directory. This provides us with a simple file format which is easy to use both in and out of Delphi. My inifile has the following syntax:

[QUERIES]
1=SELECT CAPITAL FROM COUNTRY WHERE NAME = 'Argentina'
2=SELECT NAME FROM COUNTRY WHERE CONTINENT = 'South America'

To perform the query call the ExecuteQuery procedure which in turn will call the GetQuery function. ExecuteQuery must be passed the following paramaters:

myQuery : TQuery  - TQuery component used to perform query
queryID : integer - ID number in inifile for the SQL satement
myDB : string     - optional Database Name

ExecuteQuery(qryRuntime, 1, );
ExecuteQuery(qryRuntime, 2, 'DBDEMOS');

Now for the code:

uses IniFiles;

const
  queryFileName = 'queries.ini';

procedure ExecuteQuery(myQuery: TQuery; const queryID: integer; const myDB: string =
  '');
{performs query getting SQL statement at runtime from inifile}
begin
  if not (myDB = '') then
    myQuery.DatabaseName := myDB;
  try
    myQuery.Close;
    myQuery.SQL.Clear;
    myQuery.SQL.Add(GetQuery(queryID));
    myQuery.Open;
  except
    on E: Exception do
      MessageDlg(E.message, mtError, [mbYes], 0);
  end; {try..except}
end; {procedure ExecuteQuery}

function GetQuery(const qID: integer): string;
{reads SQL statement from inifile}
var
  DirPath: string;
  queryIni: TIniFile;
begin
  DirPath := ExtractFilePath(ParamStr(0));
  queryIni := TIniFile.Create(DirPath + queryFileName);
  try
    if not (queryIni.ValueExists('QUERIES', IntToStr(qID))) then
      raise Exception.Create('ERROR: Query ID not found in file!')
    else
      result := queryIni.ReadString('QUERIES', IntToStr(qID), '');
  finally
    queryIni.Free;
  end; {try..finally}
end; {function GetQuery}

Finally, to avoid having to look up long lists of query IDs when programming, incorporate them into a unit of constant values so that you can use code like the following:

ExecuteQuery(qryRuntime, GET_CAPITAL, );
ExecuteQuery(qryRuntime, GET_COUNTRIES, 'DBDEMOS');

<< Back to main page