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
  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;
  p: Pvalue;
  v: Tvalue;
  Connection: TSQLConnection;
begin
  real := TSQLClientDataSet.Create(nil);
  result := DataSet_alloc(This, real);
  SQLClientDataSet_setup(result, real);

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

  ap_obj_call_init(result, argc, argv);
end;

function SQLClientDataSet_get_params(This: Tvalue): Tvalue; cdecl;
var
  real: TSQLClientDataSet;
begin
  real := ap_data_get_struct(This);
  // ap-dev: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);
  DefineAttrGet(cSQLClientDataSet, 'params', SQLClientDataSet_get_params);
  rb_define_method(cSQLClientDataSet, 'fetch_params', @SQLClientDataSet_fetch_params, 0);
end;

end.
