unit uSQLTable;

interface

uses Rubies, SqlExpr;

var
  cSQLTable: Tvalue;

function ap_cSQLTable: Tvalue;
function ap_iSQLTable(real: TSQLTable; owner: Tvalue): Tvalue;
procedure Init_SQLTable;

implementation

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

function ap_cSQLTable: Tvalue;
begin
  result := cSQLTable;
end;

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

function SQLTable_alloc(This: Tvalue; real: TSQLTable): Tvalue;
begin
  result := ChildAlloc(This, real);
  SQLTable_setup(result, real);
end;

function ap_iSQLTable(real: TSQLTable; owner: Tvalue): Tvalue;
begin
  result := SQLTable_alloc(cSQLTable, real);
  ap_owner(result, owner);
end;

function ap_iSQLTable_v(var obj; owner: Tvalue): Tvalue;
begin
  result := ap_iSQLTable(TSQLTable(obj), owner);
end;

function SQLTable_new(argc: integer; argv: Pointer; This: Tvalue): Tvalue; cdecl;
var
  real: TSQLTable;
  conn: TSQLConnection;
  v:Tvalue;
  args: array of Tvalue;
begin
  real := TSQLTable.Create(nil);
  result := DataSet_alloc(This, real);
  SQLTable_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.TableName := 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;

function SQLTable_get_index_names(This: Tvalue): Tvalue; cdecl;
begin
  result := ap_StringList_new;
  TSQLTable(ap_data_get_struct(This)).GetIndexNames(dl_Strings(result));
end;

procedure Init_SQLTable;
begin
  cSQLTable := DefinePersistentClass(ap_mRDB, TSQLTable, ap_cDataSet, nil);
  DefineSingletonMethod(cSQLTable, 'new', SQLTable_new);
  rb_define_method(cSQLTable, 'get_index_names', @SQLTable_get_index_names, 0);
  rb_define_alias( cSQLTable, 'index_names', 'get_index_names');
end;

end.
