{##############################################################################}
{# NexusDB: runSQL.nxscript                                                   #}
{# Copyright (c) Nexus Database Systems Pty. Ltd. %COPYRIGHT%                 #}
{# All rights reserved.                                                       #}
{##############################################################################}
{# NexusDB: Generic Server side script to run SQL commands                    #}
{##############################################################################}
procedure WriteCommandLine;
begin
  Output.Writeln('');
  Output.Writeln('Usage:');
  Output.Writeln('');
  Output.Writeln('runsql /database:dbname /sql:"select * from t1" [/delimiter:%20,] [/qualifier:%22]');
  Output.Writeln('');
  Output.Writeln('');
end;

var
  aSession: TnxSession;
  adb: TnxDatabase;
  aQuery: TnxQuery;
  i: integer;
  Start: Cardinal;
  dbName: String;
  delimiter: string;
  qualifier: string;
begin
  if CmdParams.IndexOf('/?')>-1 then
  begin
    WriteCommandLine;
    exit;
  end;

  delimiter:=ServerDecode(CmdParams.Values['/Delimiter']);
  if delimiter='' then
    delimiter:=',';
  qualifier:=ServerDecode(CmdParams.Values['/Qualifier']);

  Start:=GetTickCOunt;
  aSession:=TnxSession.Create(nil);
  adb:=TnxDatabase.Create(nil);
  aQuery:=TnxQuery.Create(nil);
  try
    aSession.ServerEngine:=ServerEngine;
    aSession.Active:=true;
    dbName:=CmdParams.Values['/Database'];
    if dbName='' then
    begin   
      WriteCommandLine;
      raise(-1, 'No database specified');
    end;
    adb.AliasName:=dbName;
    adb.Session:=aSession;
    adb.Open;
    aQuery.Database:=adb;
    aQuery.SQL.Text:=CmdParams.Values['/SQL'];
    aQuery.Open; 
    while not aQuery.eof do
    begin
      for i:=0 to aQuery.FieldCount-1 do
      begin
        Output.Write(qualifier+aQuery.Fields.Fields[i].AsString+qualifier);
        if i<aQuery.FieldCount-1 then
          Output.Write(delimiter);
      end;
      Output.WriteLn('');
      aQuery.Next;
    end;
    Start:= GetTickCount-Start;
    if CmdParams.IndexOf('/Debug')>-1 then
      Output.WriteLn('Processing time: '+inttostr(start)+' ms');
  finally
    aQuery.Free;
    adb.free;
    aSession.Free;
  end;
end.

