(* Collection of code snippets by Arne Vajhøj *)
(* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) *)
[inherit('psqlitedir:sqlite', 'psqlitedir:psqlite')]
program list_after_2(input, output);

%include 'order.pas'

var
   con : sqlite_ptr;
   sel : sqlite_stmt_ptr;
   res : array [1..1000] of order;
   count : integer;
   lastid : integer;
   i, j : integer;

begin
   con := psqlite_open('order.db');
   sel := psqlite_prepare(con, 'SELECT myorder.id,myorder.customer,orderline.id,orderline.orderid,orderline.item,orderline.qty FROM myorder JOIN orderline ON myorder.id = orderline.orderid');
   count := 0;
   lastid := -1;
   while psqlite_step_query(sel) do begin
      if psqlite_column_int(sel, 0) <> lastid then begin
         lastid := psqlite_column_int(sel, 0);
         count := count + 1;
         res[count].id := psqlite_column_int(sel, 0);
         res[count].customer := psqlite_column_text(sel, 1);
         res[count].nlines := 0;
      end; 
      res[count].nlines := res[count].nlines + 1;
      res[count].line[res[count].nlines].id := psqlite_column_int(sel, 2);
      res[count].line[res[count].nlines].orderid := psqlite_column_int(sel, 3);
      res[count].line[res[count].nlines].item := psqlite_column_text(sel, 4);
      res[count].line[res[count].nlines].qty := psqlite_column_int(sel, 5);
   end;
   psqlite_finalize(sel);
   psqlite_close(con);
   for i := 1 to count do begin
      writeln(res[i].id:1, ' ', res[i].customer);
      for j := 1 to res[i].nlines do begin
         writeln('  ', res[i].line[j].item, ': ', res[i].line[j].qty);
      end;
   end;
end.
