with Ada.Text_IO;           use Ada.Text_IO;
with GNATCOLL.SQL;          use GNATCOLL.SQL;
with GNATCOLL.SQL.Exec;     use GNATCOLL.SQL.Exec;
with GNATCOLL.SQL.Sqlite;
with GNATCOLL.Traces;       use GNATCOLL.Traces;

procedure SQLite_Test is
   Descr : Database_Description;
   DB    : Database_Connection;

   type Child_Cursor is new Forward_Cursor with null record;

   Insert : Prepared_Statement :=
     Prepare ("insert into Bar values ($1, $2, $3)");
   Query  : Prepared_Statement :=
     Prepare ("select * from Bar order by 1", Index_By => 1);
   DC     : Direct_Cursor;
   FC     : Child_Cursor;

   procedure Process_Query (RC : in out Forward_Cursor'Class) is
   begin
      RC.Fetch (DB, Query);

      while RC.Has_Row loop
         Put_Line
           (RC.Value (0) & ' ' & RC.Value (1) & ' ' & RC.Value (2)
            & Long_Float'Image (RC.Long_Float_Value (2)));
         RC.Next;
      end loop;

      Put_Line ("Processed" & Integer'Image (RC.Processed_Rows));
   end Process_Query;

   procedure Find (Value : String) is
   begin
      DC.Find (Value);

      Put (Value & ' ');

      if DC.Has_Row then
         Put_Line ("Found " & DC.Value (0));
      else
         Put_Line ("Not found");
      end if;
   end Find;

begin
   GNATCOLL.Traces.Parse_Config_File;
   Descr := Sqlite.Setup (":memory:");
   DB := Descr.Build_Connection;

   DB.Execute ("create table bar (id string, name string, value float)");

   if not Check_Connection (DB) then
      Put_Line ("Check_Connection should return True");
   end if;

   for J in 0 .. 9 loop
      DB.Execute
        (Insert,
         (1 => +J, 2 => +('N' & J'Img),
          3 => As_Long_Float (Long_Float (J) / 3.0)));
   end loop;

   DB.Commit;

   Process_Query (FC);
   Process_Query (DC);

   Find ("N 4");
   Find ("---");

end SQLite_Test;
