unit uSQLDataSet;

interface

uses Rubies, SqlExpr;

var
  cSQLDataSet: Tvalue;

function dl_SQLDataSet(v: Tvalue): TSQLDataSet;
function ap_cSQLDataSet: Tvalue;
function ap_iSQLDataSet(real: TSQLDataSet; owner: Tvalue): Tvalue;
procedure Init_SQLDataSet;

implementation

uses SysUtils, DB, uDefUtils, Pythia{, uDataSet}, uRDBExt{, uFieldDef, uIndexDef}, uParam;

function dl_SQLDataSet(v: Tvalue): TSQLDataSet;
begin
  ap_data_get_object(v, TSQLDataSet, Result);
end;

function ap_cSQLDataSet: Tvalue;
begin
  result := cSQLDataSet;
end;

procedure SQLDataSet_setup(obj: Tvalue; real: TSQLDataSet);
begin
  DataSet_setup(obj, real);
  rb_iv_set(obj, '@index_defs', ap_iIndexDefs(real.IndexDefs, obj));
end;

function SQLDataSet_alloc(This: Tvalue; real: TSQLDataSet): Tvalue;
begin
  result := ChildAlloc(This, real);
  SQLDataSet_setup(result, real);
end;

function ap_iSQLDataSet(real: TSQLDataSet; owner: Tvalue): Tvalue;
begin
  result := SQLDataSet_alloc(cSQLDataSet, real);
  ap_owner(result, owner);
end;

function ap_iSQLDataSet_v(var obj; owner: Tvalue): Tvalue;
begin
  result := ap_iSQLDataSet(TSQLDataSet(obj), owner);
end;

function SQLDataSet_new(argc: integer; argv: Pointer; This: Tvalue): Tvalue; cdecl;
var
  real: TSQLDataSet;
  conn: TSQLConnection;
  v:Tvalue;
  args: array of Tvalue;
begin
  real := TSQLDataSet.Create(nil);
  result := DataSet_alloc(This, real);
  SQLDataSet_setup(result, real);
  if argc > 0 then begin
    SetLength(args, argc);
    args := argv;
    try
      if args[0] <> Qnil then begin
        v := args[0];
        rb_iv_set(result, '@sql_connection', v);
        ap_data_get_object(v, TSQLConnection, conn);
        real.SQLConnection := conn;
      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;
  rb_obj_call_init(result, argc, argv);
end;

procedure Init_SQLDataSet;
begin
  DefineConstSetType(ap_mRDB, TypeInfo(TSQLCommandType));

  cSQLDataSet := DefinePersistentClass(ap_mRDB, TSQLDataSet, ap_cDataSet, nil);
  DefineSingletonMethod(cSQLDataSet, 'new', SQLDataSet_new);
end;

end.
