Advertisement
maiconsaraiva

Função semelhante ao antigo "BatchMove" no Delphi

Oct 15th, 2019
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 4.39 KB | None | 0 0
  1. function BatchMoveEx(AOrigem,ADestino: TDataSet; StopOnError : Boolean;
  2.   AbortOnFieldNoExist : Boolean = False; bAppend : Boolean=False):Integer;
  3.  
  4. implementation
  5.  
  6.  
  7. { BatchMoveEx criado para copiar registro de AOrigem para ADestino de forma fácil
  8.  e dinâmica, uso este nome por que o método se assemelha ao BatchMove do Interbase
  9.  
  10.  Autor; Maicon Saraiva}
  11. function BatchMoveEx(AOrigem,ADestino: TDataSet; StopOnError : Boolean;
  12.   AbortOnFieldNoExist : Boolean = False; bAppend : Boolean=False):Integer;
  13. var  i : Integer;
  14.      AFieldDest, AFieldO : TField;
  15.      ListaErro : TStringList;
  16. begin
  17.   {
  18.    IMPORTANTE: Por enquanto apenas insere os registros.
  19.  
  20.   StopOnError = Se true vai abortar a operação em caso de qualquer erro.
  21.   AbortOnFieldNoExist: Se false continua mesmo que em Destino tenha algum campo que não exista em Origem.
  22.           //O padrão é "false" por que nem sempre Origem precisará ter os mesmos campos que destino.
  23.   bAppend: Se True então permite que AOrigem já tenha dados (executa um append)
  24.  
  25.    IMPORTANTE/REGRAS:
  26.    1. ADestino e AOrigem já devem estar abertos;
  27.    2. ADestino não deve ter nenhum registro (você deve limpar ele antes)
  28.    3. Todos os campos existentes em ADestino precisam existir em AOrigem,
  29.      quando não puder ter certeza se existe ou não, uma alternativa é setar o StopOnError para False
  30.    4. Já AOrigem pode até ter mais campos que o ADestino, já que ADestino pode
  31.       não precisar de algum campo que existem em AOrigem.
  32.   }
  33.  
  34.  try
  35.   try
  36.     Result := 0;
  37.     AOrigem.DisableControls;
  38.     ADestino.DisableControls;
  39.     ListaErro := TStringList.Create;
  40.  
  41.     //Verificação de segurança
  42.     if (ADestino.RecordCount>0) and (bAppend=False) then
  43.      begin
  44.       Raise Exception.Create('Erro na função uController_DB.BatchMoveEx. '+#13+#10+
  45.         'ADestino não pode ter nehum registro ao executar esta função.');
  46.      end;
  47.  
  48.     if AOrigem.IsEmpty then
  49.      begin
  50.       Result := 0;
  51.      end
  52.     else
  53.     begin
  54.      AOrigem.First;
  55.      while not AOrigem.Eof do
  56.      begin
  57.       try
  58.        ADestino.Append;
  59.        for i:=0 to AOrigem.Fields.Count-1 do
  60.        begin
  61.         AFieldDest := ADestino.FindField(AOrigem.Fields[i].FieldName);
  62.         AFieldO    := AOrigem.Fields[i];
  63.         if AFieldDest=nil then //Se nil, significa que o campo não existe no destino
  64.          begin
  65.           {Se for para abortar caso algum campo em origem não exista em destino
  66.            Obs: o default é "false" (não abortar), pois as vezes teremos algum campo em AOrigem que não teremos no ADestino
  67.            IMPORTANTE: É importante verificar bem os campos antes de qualquer coisa, pois caso o campo não tenha só será emitido um alerta no modo DEBUG
  68.           }
  69.           if AbortOnFieldNoExist then
  70.             Raise Exception.Create('Erro no BatchMoveEX. "'+AOrigem.Name+'", campo "'+AFieldO.FieldName
  71.               +'" não existe no dataset de destino: "'+ADestino.Name+'"')
  72.           else
  73.            begin
  74.               //Se não for abortar não faz nada, mas se estiver em modo de debug emite um alerta para o Dev.
  75.               {$IFDEF DEBUG}
  76.             //  ListaErro.Add('Erro no BatchMove. "'+AOrigem.Name+'", campo "'+AFieldO.FieldName
  77.             //  +'" não existe no dataset de destino: "'+ADestino.Name+'"');
  78.               {$ENDIF}
  79.            end;
  80.  
  81.  
  82.          end
  83.         else
  84.           try
  85.               if AFieldDest.FieldKind=fkData then
  86.                 AFieldDest.Value :=  AFieldO.Value;
  87.           except  //Except no Field
  88.            on E:Exception do
  89.            begin
  90.             if StopOnError then
  91.               Raise Exception.Create(e.Message);
  92.            end;
  93.           end;
  94.        end; //for
  95.        ADestino.Post;
  96.  
  97.        {$IFDEF DEBUG}
  98. //         Erro_IfDebug(ListaErro.Text);
  99.        {$ENDIF}
  100.  
  101.       except //Except no Registro (geralmente no Post;)
  102.          on E:Exception do
  103.          begin
  104.            if ADestino.State in [dsEdit,dsInsert] then
  105.               ADestino.Cancel;
  106.            if StopOnError then
  107.               Raise Exception.Create(e.Message);
  108.          end;
  109.       end;
  110.       AOrigem.Next;
  111.      end;
  112.      Result := ADestino.RecordCount;
  113.     end;
  114.  
  115.  
  116.  
  117.  
  118.   except
  119.     on E:Exception do
  120.     begin
  121.       Result := -1;
  122.       Raise Exception.Create(e.Message);
  123.     end;
  124.    end;
  125.  finally
  126.   AOrigem.EnableControls;
  127.   ADestino.EnableControls;
  128.   ListaErro.Free;
  129.  end;
  130.  
  131. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement