Ajuda Migrar DBX para Firedac

25/12/2016

0

Alguém poderia me auxiliar como faço para poder migrar esta unit do DBX para Firedac.


unit FDPoo;

interface

uses Atributos, Rtti, System.SysUtils, SQLExpr, TypInfo, DBXCommon, VO, System.Classes,
    Generics.Collections, UDataModuleConexao;

type
  TFDPoo = class
  private
    class function FormatarFiltro(pFiltro: String): String;
    class function ValorPropriedadeObjeto(pObjeto: TObject; pCampo: String): Variant;
  public
    class function Inserir(pObjeto: TObject): Integer;
    class function Alterar(pObjeto: TObject): Boolean; overload;
    class function Alterar(pObjeto, pObjetoOld: TObject): Boolean; overload;
    class function Excluir(pObjeto: TObject): Boolean;
    class function Consultar<T: class>(pFiltro: String; pPagina: String = '0'; pConsultaCompleta: Boolean = False): TObjectList<T>; overload;
    class function Consultar(pObjeto: TObject; pFiltro: String; pPagina: String; var pDBXCommand: TDBXCommand): TDBXReader; overload;
    class function Consultar(pConsulta: String; pFiltro: String; pPagina: String): TDBXReader; overload;
    class function ConsultarUmObjeto<T: class>(pFiltro: String; pConsultaCompleta: Boolean): T;

    class procedure PopularObjetosRelacionados(pObjeto: TVO);

    class function ComandoSQL(pConsulta: String): Boolean;
    class function SelectMax(pTabela: String; pFiltro: String): Integer;
    class function SelectMin(pTabela: String; pFiltro: String): Integer;
    class function SelectCount(pTabela: String): Integer;
  end;

var
  Conexao: TSQLConnection;
  Query: TSQLQuery;
  ConsultaCompleta: Boolean;

implementation

uses
  Constantes;

{ TFDPoo }

{$Region 'Infra'}
class function TFDPoo.FormatarFiltro(pFiltro: String): String;
begin
  Result := pFiltro;
  Result := StringReplace(Result, '*', '%', [rfReplaceAll]);
  Result := StringReplace(Result, '|', '/', [rfReplaceAll]);
  Result := StringReplace(Result, '\\"', '"', [rfReplaceAll]);
end;

class function TFDPoo.ValorPropriedadeObjeto(pObjeto: TObject; pCampo: String): Variant;
var
  Contexto: TRttiContext;
  Tipo: TRttiType;
  Atributo: TCustomAttribute;
  Propriedade: TRttiProperty;
begin
  Result := 0;
  Contexto := TRttiContext.Create;
  try
    Tipo := Contexto.GetType(pObjeto.ClassType);

    for Propriedade in Tipo.GetProperties do
    begin
      for Atributo in Propriedade.GetAttributes do
      begin
        // se está pesquisando pelo ID
        if Atributo is TId then
        begin
          if (Atributo as TId).NameField = pCampo then
          begin
            Result := Propriedade.GetValue(pObjeto).AsInteger;
          end;
        end;

        // se está pesquisando por outro campo
        if Atributo is TColumn then
        begin
          if (Atributo as TColumn).Name = pCampo then
          begin
            if (Propriedade.PropertyType.TypeKind in [tkInteger, tkInt64]) then
              Result := Propriedade.GetValue(pObjeto).AsInteger
            else if (Propriedade.PropertyType.TypeKind in [tkString, tkUString]) then
              Result := Propriedade.GetValue(pObjeto).AsString;
          end;
        end;
      end;
    end;
  finally
    Contexto.Free;
  end;
end;

class procedure TFDPoo.PopularObjetosRelacionados(pObjeto: TVO);
var
  i: Integer;
  DBXReader: TDBXReader;
  DBXCommand: TDBXCommand;
  Contexto: TRttiContext;
  Tipo: TRttiType;
  Atributo: TCustomAttribute;
  Propriedade: TRttiProperty;

  NomeTipoObjeto: String;
  NomeClasseObjeto: String;

  Lista: TObjectList<TVO>;
  ItemLista: TVO;

  ObjetoLocal: TVO;
  RttiInstanceType: TRttiInstanceType;
  ObjetoLocalRtti: TValue;
begin
  Contexto := TRttiContext.Create;
  try
    Tipo := Contexto.GetType(pObjeto.ClassType);

    // Percorre propriedades
    for Propriedade in Tipo.GetProperties do
    begin
      // Percorre atributos
      for Atributo in Propriedade.GetAttributes do
      begin

        // Verifica se o atributo é um atributo de associação para muitos
        if Atributo is TManyValuedAssociation then
        begin
          // Se for uma consulta completa, carrega as listas
          if ConsultaCompleta then
          begin
            // Se a propriedade for uma classe
            if Propriedade.PropertyType.TypeKind = tkClass then
            begin
              NomeTipoObjeto := Propriedade.PropertyType.Name;
              if (Pos('TList', NomeTipoObjeto) > 0) or (Pos('TObjectList', NomeTipoObjeto) > 0) then
              begin
                // Captura o tipo de classe da lista (TList<Unit.TNomeClasse>)
                i := Pos('<', NomeTipoObjeto);
                NomeClasseObjeto := Copy(NomeTipoObjeto, i + 1, Length(NomeTipoObjeto) - 1 - i);

                try
                  // Cria objeto temporário
                  RttiInstanceType := (Contexto.FindType(NomeClasseObjeto) as TRttiInstanceType);
                  ObjetoLocalRtti := RttiInstanceType.GetMethod('Create').Invoke(RttiInstanceType.MetaclassType,[]);
                  ObjetoLocal := TVO(ObjetoLocalRtti.AsObject);
                  if Assigned(ObjetoLocal) then
                  begin
                    Lista := TObjectList<TVO>(Propriedade.GetValue(pObjeto).AsObject);

                    // Se a lista tiver sido instanciada
                    if Assigned(Lista) then
                    begin
                      // Consulta a lista de objetos
                      DBXReader := Consultar(ObjetoLocal, (Atributo as TManyValuedAssociation).ForeingColumn + ' = ' + QuotedStr( String( ValorPropriedadeObjeto(pObjeto, (Atributo as TManyValuedAssociation).LocalColumn))), '-1', DBXCommand);
                      try
                        while DBXReader.Next do
                        begin
                          // Cria nova instância do objeto temporário
                          ObjetoLocalRtti := RttiInstanceType.GetMethod('Create').Invoke(RttiInstanceType.MetaclassType,[]);
                          ItemLista := TVO(ObjetoLocalRtti.AsObject);
                          // Popula Objeto
                          ItemLista := VOFromDBXReader(TVO(ItemLista), DBXReader);
                          // Inclui objeto na lista
                          Lista.Add(ItemLista);
                          // Continua populando as associações dentro do objeto até que todos sejam populados recursivamente
                          PopularObjetosRelacionados(TVO(ItemLista));
                        end;
                      finally
                        FreeAndNil(DBXReader);
                        FreeAndNil(DBXCommand);
                      end;
                    end;
                    // Destroi objeto temporário
                    FreeAndNil(ObjetoLocal);
                  end;
                finally
                end;
              end;
            end;
          end;
        end

        // Verifica se o atributo é um atributo de associação para uma classe
        else if Atributo is TAssociation then
        begin
          // Se a propriedade for uma classe
          if Propriedade.PropertyType.TypeKind = tkClass then
          begin
            // Captura o tipo de classe da lista (Unit.TNomeClasse)
            NomeClasseObjeto := Propriedade.PropertyType.QualifiedName;

            // Verifica se o objeto já está instanciado
            ObjetoLocal := Propriedade.GetValue(pObjeto).AsObject as TVO;

            // Se conseguiu capturar uma instância do objeto, popula...
            if Assigned(ObjetoLocal) then
            begin
              // Consulta o objeto relacionado
              DBXReader := Consultar(ObjetoLocal, (Atributo as TAssociation).ForeingColumn + ' = ' + QuotedStr( String( ValorPropriedadeObjeto(pObjeto, (Atributo as TAssociation).LocalColumn))), '0', DBXCommand);
              try
                if DBXReader.Next then
                begin
                  // Popula Objeto
                  ObjetoLocal := VOFromDBXReader(ObjetoLocal, DBXReader);
                  // Inclui objeto no objeto principal
                  Propriedad

Ricardo Pereira

Ricardo Pereira

Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar