unit uSQLClientDataSet;

interface

uses Rubies, SqlExpr, DBLocalS;

var
  cSQLClientDataSet: Tvalue;

procedure Init_SQLClientDataSet;

implementation

uses
  SysUtils, Classes, DB,
{$IFDEF VCL}
  Graphics,
{$ELSE}
  QGraphics,
{$ENDIF}
  uDefUtils, Pythia,
  uRDBExt{, RDBHandle, uDataSet, uClientDataSet, uParam, uIndexDef};

procedure SQLClientDataSet_setup(obj: Tvalue; real: TSQLClientDataSet);
begin
  //ClientDataSet_setup(obj, real);
  DataSet_setup(obj, real);
  rb_iv_set(obj, '@index_defs', ap_iIndexDefs(real.IndexDefs, obj));
end;

function SQLClientDataSet_new(argc: integer; argv: Pointer; This: Tvalue): Tvalue; cdecl;
var
  real: TSQLClientDataSet;
  args: array of Tvalue;
  Connection: TSQLConnection;
begin
  real := TSQLClientDataSet.Create(nil);
  result := DataSet_alloc(This, real);
  SQLClientDataSet_setup(result, real);
  //DataSet_setup(result, real);

  if argc > 0 then
  begin
    SetLength(args, argc);
    args := argv;
    try
      if args[0] <> Qnil then
      begin
        ap_data_get_object(args[0], TSQLConnection, Connection);
        real.DBConnection := Connection;
      end;
      if argc > 1 then
      begin
        real.CommandText := dl_String(args[1]);
      end;
    except
      on E: Exception do
        ap_raise(ap_eDatabaseError, E.message);
    end;
  end;

  ap_obj_call_init(result, argc, argv);
end;

function SQLClientDataSet_open(argc: integer; argv: Pointer; This: Tvalue): Tvalue; cdecl;
var
  real: TSQLClientDataSet;
  args: array of Tvalue;
begin
//rb_p(ap_String('SQLClientDataSet_open'));
  real := ap_data_get_struct(This);
  if argc > 0 then
  begin
    SetLength(args, argc);
    args := argv;
    real.Close;
    real.CommandText := dl_String(args[0]);
  end;
  real.Open;
  result := This;
end;

function SQLClientDataSet_get_params(This: Tvalue): Tvalue; cdecl;
var
  real: TSQLClientDataSet;
begin
  real := ap_data_get_struct(This);
  //
  // http://www.freeml.com/message/ap-dev@freeml.com/0847
  try
     if real.Params.Count = 0 then real.Open;
  except
    real.Close;
  end;
  //
  result := ap_iParams(real.Params, This);
end;

function SQLClientDataSet_fetch_params(This: Tvalue): Tvalue; cdecl;
var
  real: TSQLClientDataSet;
begin
  real := ap_data_get_struct(This);
  real.FetchParams;
  result := This;
end;

procedure Init_SQLClientDataSet;
begin
  cSQLClientDataSet := DefinePersistentClass(ap_mRDB, TSQLClientDataSet, ap_cClientDataSet, nil);
  DefineSingletonMethod(cSQLClientDataSet, 'new', SQLClientDataSet_new);
//  rb_define_method(cSQLClientDataSet, 'open', @SQLClientDataSet_open, -1);
  DefineAttrGet(cSQLClientDataSet, 'params', SQLClientDataSet_get_params);
  rb_define_method(cSQLClientDataSet, 'fetch_params', @SQLClientDataSet_fetch_params, 0);
end;

end.
