(* Collection of code snippets by Arne Vajhøj *)
(* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) *)
unit dbu;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, SQLDB;

type
  Problem = class(Exception);
  DB = class(TObject)
    public
      procedure setup;
      procedure check;
      procedure teardown;
      function get_connection : TSQLConnection; virtual; abstract;
      procedure test; virtual; abstract;
      class procedure demo(dbi : DB);
  end;

implementation

procedure DB.setup;

var
   con : TSQLConnection;
   tx : TSQLTransaction;
   q : TSQLQuery;

begin
  con := get_connection;
  tx := TSQLTransaction.Create(nil);
  con.Transaction := tx;
  q := TSQLQuery.Create(nil);
  q.DataBase := con;
  q.SQL.Text := 'INSERT INTO tblsrc VALUES(1, 10)';
  q.ExecSQL;
  q.SQL.Text := 'INSERT INTO tbltrg VALUES(1, 0)';
  q.ExecSQL;
  q.Close;
  q.Free;
  tx.Commit;
  tx.Free;
  con.Close;
  con.Free;
end;

procedure DB.check;

var
   con : TSQLConnection;
   tx : TSQLTransaction;
   q : TSQLQuery;

begin
  con := get_connection;
  tx := TSQLTransaction.Create(nil);
  con.Transaction := tx;
  q := TSQLQuery.Create(nil);
  q.DataBase := con;
  q.SQL.Text := 'SELECT val FROM tblsrc WHERE id = 1';
  q.Open;
  writeln('source val = ', q.FieldByName('val').AsInteger);
  q.Close;
  q.Free;
  q := TSQLQuery.Create(nil);
  q.DataBase := con;
  q.SQL.Text := 'SELECT val FROM tbltrg WHERE id = 1';
  q.Open;
  writeln('target val = ', q.FieldByName('val').AsInteger);
  q.Close;
  q.Free;
  tx.Commit;
  tx.Free;
  con.Close;
  con.Free;
end;

procedure DB.teardown;

var
   con : TSQLConnection;
   tx : TSQLTransaction;
   q : TSQLQuery;

begin
  con := get_connection;
  tx := TSQLTransaction.Create(nil);
  con.Transaction := tx;
  q := TSQLQuery.Create(nil);
  q.DataBase := con;
  q.SQL.Text := 'DELETE FROM tblsrc WHERE id = 1';
  q.ExecSQL;
  q.SQL.Text := 'DELETE FROM tbltrg WHERE id = 1';
  q.ExecSQL;
  q.Close;
  q.Free;
  tx.Commit;
  tx.Free;
  con.Close;
  con.Free;
end;

class procedure DB.demo(dbi : DB);

begin
  dbi.setup;
  dbi.check;
  dbi.test;
  dbi.check;
  dbi.teardown;
end;

end.

