{ DISQLite3 example project showing how retrieve data from a table and write it
  to the console. It uses plain DISQLite3 API calls.

  This demo uses the table created by the Create_Table demo. Compile and execute
  the Create_Table demo at least once before running the project.

  Visit the DISQLite3 Internet site for latest information and updates:

    http://www.yunqa.de/delphi/

  Copyright (c) 2005-2009 Ralf Junker, The Delphi Inspiration <delphi@yunqa.de>

------------------------------------------------------------------------------ }

program DISQLite3_Show_Table;

{$I DI.inc}
{$I DISQLite3.inc}

{$APPTYPE CONSOLE}

uses
  {$IFDEF FastMM}FastMM4, {$ENDIF}disystemcompat, SysUtils, DISQLite3Api,
  DISQLite3_Demos_Common in '..\DISQLite3_Common_Units\DISQLite3_Demos_Common.pas';

//------------------------------------------------------------------------------

{ This is the callback function triggered for each row in the table.
  We use it to write all fields of a record to the console. }
function WriteRowCallback(UserData: Pointer; ColumnCount: Integer; ColumnValues, ColumnNames: PPUtf8CharArray): Integer;
var
  i: Integer;
begin
  for i := 0 to ColumnCount - 1 do
    begin
      if i > 0 then Write(' | ');
      Write(ColumnValues[i]);
    end;
  WriteLn;
  Result := 0; // Return 0 to retrieve the next record, 1 to abort.
end;

//------------------------------------------------------------------------------

begin
  { Disable FPU exceptions. No need to restore, setting is process specific. }
  Set8087CW($133F);

  try
    { Initialize the DISQLite3 library prior to using any other DISQLite3
      functionality. See also sqlite3_shutdown() below.}
    sqlite3_initialize;
    try
      Open_Demo_Database;
      try
        { sqlite3_exec can trigger a callback function for each record returned
          by an SQL statement. We use this callback function to write all fields
          to the console. }

        WriteLn('Plain table, no sorting:');
        WriteLn;
        { Error? Compile and run the Create_Table demo to set up the required tables. }
        sqlite3_check(sqlite3_exec(DB,
          'SELECT * from People;',
          WriteRowCallback, // <- Callback function from DISQLite3_Demos_Common.pas!
          nil, nil),
          DB);

        WriteLn;
        WriteLn('Table sorted by LastName, then by FirstName:');
        WriteLn;
        sqlite3_check(sqlite3_exec(DB,
          'SELECT * from People ORDER BY LastName, FirstName;',
          WriteRowCallback, // <- Callback function from DISQLite3_Demos_Common.pas!
          nil, nil),
          DB);

      finally
        Close_Demo_Database;
      end;

    finally
      { Deallocate any resources that were allocated by
        sqlite3_initialize() above. }
      sqlite3_shutdown;
    end;

  except
    on e: Exception do
      WriteLn(e.Message);
  end;

  WriteLn;
  WriteLn('Done - Press ENTER to Exit');
  ReadLn;
end.

