unit uSQLTable;

{$I heverdef.inc}

interface

uses Rubies, SqlExpr;

var
  cSQLTable: Tvalue;

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

implementation

uses
{$IFDEF COMP10_UP}
  WideStrings,
{$ENDIF}
  SysUtils, Classes, uDefUtils, Pythia, uRDBExt;

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;
  p: Pvalue;
begin
  real := TSQLTable.Create(nil);
  result := DataSet_alloc(This, real);
  SQLTable_setup(result, real);
  if argc > 0 then begin
    p := argv;
    try
      if p^ <> Qnil then begin
        v := p^; inc(p);
        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(p^);
      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;
var
  names: TStrings;
{$IFDEF COMP10_UP}
  wnames: TWideStrings;
  i: Integer;
{$ENDIF}
begin
  result := ap_StringList_new;
  names := dl_Strings(result);
{$IFDEF COMP10_UP}
  wnames := TWideStringList.Create;
  try
    TSQLTable(ap_data_get_struct(This)).GetIndexNames(wnames);
    for i := 0 to wnames.Count - 1 do
      names.Add(wnames[i]);
  finally
    wnames.Free;
  end;
{$ELSE}
  TSQLTable(ap_data_get_struct(This)).GetIndexNames(names);
{$ENDIF}
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.
