[firebase-br] Cache Updates

Rodrigo dominioinf em brturbo.com.br
Sáb Dez 2 08:21:01 -03 2006


Bom dia a todos,,

Estou migrando meu sistema para delphi 7, ele funciona todo em ibx, só que 
quando vou compilar da um erro dizendo que o cache updates está como false, 
e realmente está, pq uso assim com delphi 6.

É algo para me preocupar?

Se alguem puder me dar um toque,

Agradecido
Rodrigo



----- Original Message ----- 
From: "Jeferson Oliveira" <jefersonfoliveira em gmail.com>
To: "FireBase" <lista em firebase.com.br>
Sent: Friday, December 01, 2006 6:15 PM
Subject: Re: [firebase-br] Melhor forma de Backup/Restore


Enio Marconcini escreveu:
> como vc implementa esses procedimentos ?

Paulo! Explicarei com uma condição: você começar a postar suas
mensagens debaixo da mensagem que deseja responder, se não fica uma
loucura para quem lê por newsgroup. :-)

Alguns métodos como AtribuirValorPadrao e AcertarIntegridade trabalham
com regras de negócio específica de cada sistema, e não cabe aqui a
publicação deles.

Seguem abaixo métodos de uso geral, espero que lhes sejam úteis.


uses
  IBQuery, IBServices;

procedure PrepararBancoParaBackup(Servidor, NomeCompletoArquivoGDB: string);
var
  IBValidation: TIBValidationService;
begin
  IBValidation := TIBValidationService.Create(nil);
  try
    IBValidation.Params.Clear;
    IBValidation.Params.Add('user_name=SYSDBA');
    IBValidation.Params.Add('password=masterkey');

    IBValidation.ServerName := UpperCase(Servidor);
    IBValidation.Protocol := TCP;
    if IBValidation.ServerName = 'LOCALHOST' then
      IBValidation.Protocol := Local;

    IBValidation.DatabaseName := NomeCompletoArquivoGDB;
    IBValidation.Options := [MendDB];
    IBValidation.Attach;
    IBValidation.Active := True;
    IBValidation.ServiceStart;
    IBValidation.Active := False;
  finally
    IBValidation.Free;
  end;
end;

procedure BackupDB(Servidor, NomeCompletoArquivoGDB: string);
var
  IBBackup: TIBBackupService;
begin
  IBBackup := TIBBackupService.Create(nil);
  try
    IBBackup.Params.Clear;
    IBBackup.Params.Add('user_name=SYSDBA');
    IBBackup.Params.Add('password=masterkey');
    IBBackup.LoginPrompt := False;

    IBBackup.ServerName := UpperCase(Servidor);
    IBBackup.Protocol := TCP;
    if IBBackup.ServerName = 'LOCALHOST' then
      IBBackup.Protocol := Local;

    IBBackup.DatabaseName := NomeCompletoArquivoGDB;
    IBBackup.BackupFile.Text := ChangeFileExt(NomeCompletoArquivoGDB, 
'.GBK');
    IBBackup.Verbose := True;
    IBBackup.Attach;
    IBBackup.Options := [NoGarbageCollection];
    IBBackup.Active := True;
    IBBackup.ServiceStart;
  {Método GetNextLine é invocado para obter cada linha do log do GBAK
   quando Vebose = True.
   Nos casos em que Verbose=False a função é chamada apenas para
   garantir que o próximo método não seja executado antes do término
   desse procedimento.
  }
    while not IBBackup.Eof do
      IBBackup.GetNextLine;
    IBBackup.Active := False;
  finally
    IBBackup.Free;
  end;
end;

procedure RestoreDB(Servidor, NomeCompletoArquivoGBK: string);
var
  IBRestore: TIBRestoreService;
begin
  IBRestore := TIBRestoreService.Create(nil);
  try
    IBRestore.Params.Clear;
    IBRestore.Params.Add('user_name=SYSDBA');
    IBRestore.Params.Add('password=masterkey');
    IBRestore.LoginPrompt := False;

    IBRestore.ServerName := UpperCase(Servidor);
    IBRestore.Protocol := TCP;
    if IBRestore.ServerName = 'LOCALHOST' then
      IBRestore.Protocol := Local;

    IBRestore.Verbose := True;
    IBRestore.Attach;
    IBRestore.Options := [Replace];
    IBRestore.DatabaseName.Add(ChangeFileExt(NomeCompletoArquivoGBK, 
'.GDB'));
    IBRestore.BackupFile.Add(NomeCompletoArquivoGBK);
    IBRestore.Active := True;
    IBRestore.ServiceStart;
    while not IBRestore.Eof do
      IBRestore.GetNextLine;
    IBRestore.Active := False;
  finally
    IBRestore.Free;
  end;
end;

function HaDesintegridade(TabelaDetalhe, TabelaMestre,
  CondicaoSubQuery: string): Boolean;
var
  ibqAcerta: TIBQuery;
begin
  //Verifica se existe na tabela Detalhe registros que violam a chave
  //por não existirem na tabela Mestre. A query é montada com base nas
  //listas de campos detalhe e master.

  Result := False;
  ibqAcerta := TIBQuery.Create(nil);
  try
    ibqAcerta.Close;
    ibqAcerta.SQL.Text := 'select  * '
      + 'from ' + TabelaDetalhe + ' A '
      + 'where not exists(select 1 '
      + '                 from ' + TabelaMestre + ' B '
      + '                 where ' + CondicaoSubQuery + ')';
    ibqAcerta.Open;
    Result := ibqAcerta.RecordCount > 0;
  finally
    ibqAcerta.Free;
  end;
end;

procedure HabilitaDesabilitaObjeto(Desativar: Boolean);
var
  EstadoObjeto: string;
  Inativo: Char;
  ibqExecutar: TIBQuery;

  procedure AlteraEstadoObjeto;
  var
    ibqObjeto: TIBQuery;
    NomeObjeto: string;
  begin
    ibqObjeto := TIBQuery.Create(nil);
    try
      ibqObjeto.Database := ibqExecutar.Database;

      ibqObjeto.SQL.Text := 'select RDB$TRIGGER_NAME As NomeObjeto '
        + 'from RDB$TRIGGERS '
        + 'where RDB$RELATION_NAME = ' + QuotedStr(TabelaDetalhe)
        + '  and RDB$TRIGGER_INACTIVE = ' + Inativo + ' '
        + '  and (RDB$SYSTEM_FLAG is null  '
        + '    or RDB$SYSTEM_FLAG = 0)  '
        + 'Order by RDB$TRIGGER_NAME ';
      ibqObjeto.Open;
      ibqObjeto.First;
      while not ibqObjeto.Eof do
      begin
        NomeObjeto := Trim(ibqObjeto.FieldByName('NomeObjeto').AsString);
        ibqExecutar.Close;
        ibqExecutar.SQL.Text := 'alter trigger ' + NomeObjeto + ' ' +
EstadoObjeto;
        try
          ibqExecutar.ExecSQL;
          ibqExecutar.Transaction.CommitRetaining;
        except
          on E: Exception do
          begin
            AdicionaAoLog('Erro na alteração da trigger: ' + NomeObjeto + '. 
'
              + E.Message);
          end;
        end;
        ibqObjeto.Next;
      end;
    finally
      ibqObjeto.Free;
    end;
  end;
begin
  if Desativar then
  begin
    EstadoObjeto := 'INACTIVE';
    Inativo := '0';
  end
  else
  begin
    EstadoObjeto := 'ACTIVE';
    Inativo := '1';
  end;
  ibqExecutar := TIBQuery.Create(nil);
  try
    ibqExecutar.Database := FDatabaseReestruturar;
    AlteraEstadoObjeto;
  finally
    ibqExecutar.Free;
  end;
end;

function ExcluirRegistrosOrfaos(TabelaDetalhe, TabelaMestre, 
ListaCamposDetalhe,
  CondicaoSubQuery: string; CampoDetalhe: string = ''): Boolean;
var
  SQLOrfaos: string;
  ibqExclusao: TIBQuery;
begin
  HabilitaDesabilitaObjeto(True);

  SQLOrfaos := 'delete from ' + TabelaDetalhe + ' A where 0 = 0 ';

  //Se chave possui somente um campo, valores nulos devem ser 
desconsiderados
  if Trim(RetornaCampo(ListaCamposDetalhe, ',', 2)) = '' then
    SQLOrfaos := SQLOrfaos + ' and ' + CampoDetalhe + ' is not null ';

  SQLOrfaos := SQLOrfaos +
    ' and not exists(select ' + CampoMaster +
    '                from ' + TabelaMaster + ' B ' +
    '                where ' + CondicaoSubQuery + ')';

  ibqExclusao := TIBQuery.Create(nil);
  try
    with ibqExclusao do
    begin
      Close;
      SQL.Text := SQLOrfaos;
      ExecSQL;
    end;
    Result := ibqExclusao.RowsAffected > 0;
  finally
    ibqExclusao.Free;
  end;

  HabilitaDesabilitaObjeto(False);
end;

Observação: Para montar os relacionamentos das tabelas detalhe e
master (CondicaoSubQuery) é necessário percorrer cada ForeignKey e
identificar os campos relacionados. Abaixo a sentença que utilizo para
esse fim:

select Detalhe.RDB$CONSTRAINT_NAME As NomeForeignKey,
idxDetalhe.RDB$FIELD_NAME As CampoDetalhe,
Master.RDB$RELATION_NAME As TabelaMaster,
idxMaster.RDB$FIELD_NAME As CampoMaster
from RDB$RELATION_CONSTRAINTS Detalhe
  left join RDB$INDEX_SEGMENTS idxDetalhe
    On (idxDetalhe.rdb$index_name = Detalhe.rdb$index_name)
  left join RDB$REF_CONSTRAINTS R
    On (R.RDB$CONSTRAINT_NAME = Detalhe.RDB$CONSTRAINT_NAME)
  left join RDB$RELATION_CONSTRAINTS Master
    On (Master.RDB$CONSTRAINT_NAME = R.RDB$CONST_NAME_UQ)
  left join RDB$INDEX_SEGMENTS idxMaster
    On (idxMaster.rdb$index_name = Master.rdb$index_name)
where Detalhe.RDB$CONSTRAINT_NAME = :NOME_FK
  and idxDetalhe.rdb$field_position = idxMaster.rdb$field_position
 Order By Detalhe.RDB$CONSTRAINT_NAME, idxDetalhe.RDB$FIELD_POSITION


Abraço!
Jeferson Oliveira

______________________________________________
FireBase-BR (www.firebase.com.br) - Hospedado em www.locador.com.br
Para editar sua configuração na lista, use o endereço 
http://mail.firebase.com.br/mailman/listinfo/lista_firebase.com.br
Para consultar mensagens antigas: http://firebase.com.br/pesquisa 






Mais detalhes sobre a lista de discussão lista