unit Aurelius.Plugin.Connection;

interface

uses
  SysUtils,
  Aurelius.Drivers.Interfaces,
  Aurelius.Plugin.Types;

type
  TASPluginConnection = class(TInterfacedObject, IASPluginConnection)
  private
    FConnection: IDBConnection;
    function CreateStatement: IASPluginStatement;
  public
    constructor Create(AConnection: IDBConnection);
  end;

  TASPluginStatement = class(TInterfacedObject, IASPluginStatement)
  private
    FConnection: IDBConnection;
    FEOF: Boolean;
    FResultSet: IDBResultSet;
  public
    function GetEOF: Boolean;
    function FieldAsString(const AFieldName: WideString): WideString;
    function FieldAsInteger(const AFieldName: WideString): integer;
    function FieldAsBoolean(const AFieldName: WideString): boolean;
    procedure Next;
    procedure Open(const SQL: WideString);
    procedure Execute(const SQL: WideString);
  public
    constructor Create(AConnection: IDBConnection);
  end;

implementation

uses
  Variants;

function VarToBool(V: Variant): Boolean;
begin
  if VarIsNull(V) then
    Result := False
  else
    Result := V;
end;

function VarToInt(V: Variant): Integer;
begin
  if VarIsNull(V) then
    Result := 0
  else
    // Avoid range check errors
    Result := Int64Rec(Int64(V)).Lo;
//    Result := V;
end;

{ TSQLConnectionModuleFactory }

constructor TASPluginConnection.Create(AConnection: IDBConnection);
begin
  FConnection := AConnection;
end;

function TASPluginConnection.CreateStatement: IASPluginStatement;
begin
  Result := TASPluginStatement.Create(FConnection);
end;

{ TSQLConnectionModule }

constructor TASPluginStatement.Create(AConnection: IDBConnection);
begin
  FConnection := AConnection;
end;

procedure TASPluginStatement.Execute(const SQL: WideString);
var
  Stmt: IDBStatement;
begin
  Stmt := FConnection.CreateStatement;
  Stmt.SetSQLCommand(SQL);
  Stmt.Execute;
end;

function TASPluginStatement.FieldAsBoolean(const AFieldName: WideString): boolean;
begin
  Result := VarToBool(FResultSet.GetFieldValue(AFieldName));
end;

function TASPluginStatement.FieldAsInteger(const AFieldName: WideString): integer;
begin
  Result := VarToInt(FResultSet.GetFieldValue(AFieldName));
end;

function TASPluginStatement.FieldAsString(const AFieldName: WideString): WideString;
begin
  Result := VarToStr(FResultSet.GetFieldValue(AFieldName));
end;

function TASPluginStatement.GetEOF: Boolean;
begin
  Result := FEOF;
end;

procedure TASPluginStatement.Next;
begin
  FEOF := not FResultSet.Next;
end;

procedure TASPluginStatement.Open(const SQL: WideString);
var
  Stmt: IDBStatement;
begin
  Stmt := FConnection.CreateStatement;
  Stmt.SetSQLCommand(SQL);
  FResultSet := Stmt.ExecuteQuery;
  Next;
end;

end.
