Last active
August 26, 2024 17:48
-
-
Save wellington1993/c5eeaf5526e6ee46f1cc5908baed44a4 to your computer and use it in GitHub Desktop.
Backup IBBackupService Delphi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses | |
SysUtils, IniFiles, Classes, ShellAPI, Windows, RegularExpressions, Dialogs, System.Threading, IBX.IBServices, IBX.IBUtils; | |
type | |
TDatabaseConfig = record | |
Server: string; | |
Port: string; | |
DatabasePath: string; | |
UserName: string; | |
Password: string; | |
BackupPath: string; | |
end; | |
function ExpandDatabasePath(const DatabasePath: string): string; | |
begin | |
if Pos('file://', DatabasePath) = 1 then | |
Result := Copy(DatabasePath, 8, Length(DatabasePath) - 7) | |
else if Pos('%', DatabasePath) > 0 then | |
Result := ExpandEnvironmentStrings(PChar(DatabasePath), nil, 0) | |
else | |
Result := ExpandFileName(DatabasePath); | |
end; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses | |
SysUtils, IniFiles, Classes, ShellAPI, Windows, RegularExpressions, Dialogs, System.Threading, IBX.IBServices, IBX.IBUtils; | |
type | |
TDatabaseConfig = record | |
Server: string; | |
Port: string; | |
DatabasePath: string; | |
UserName: string; | |
Password: string; | |
BackupPath: string; | |
end; | |
// 0.pas | |
function ExtractDatabaseConfig(const IniFileName: string): TDatabaseConfig; | |
var | |
IniFile: TIniFile; | |
DatabasePath: string; | |
Regex: TRegEx; | |
Match: TMatch; | |
begin | |
IniFile := TIniFile.Create(IniFileName); | |
try | |
DatabasePath := IniFile.ReadString('Database', 'Database', ''); | |
DatabasePath := ExpandDatabasePath(DatabasePath); | |
// Regex para capturar servidor, porta e caminho do banco de dados | |
Regex := TRegEx.Create('^(.*?)(?:/(\d+))?:(.*)$'); | |
Match := Regex.Match(DatabasePath); | |
if Match.Success then | |
begin | |
Result.Server := Match.Groups[1].Value; | |
Result.Port := Match.Groups[2].Value; | |
if Result.Port = '' then | |
Result.Port := '3050'; // Porta padrão do Firebird | |
Result.DatabasePath := Match.Groups[3].Value; | |
end | |
else | |
begin | |
Result.Server := 'localhost'; | |
Result.Port := '3050'; | |
Result.DatabasePath := DatabasePath; | |
end; | |
Result.UserName := IniFile.ReadString('Database', 'User_Name', ''); | |
Result.Password := IniFile.ReadString('Database', 'Password', ''); | |
Result.BackupPath := IniFile.ReadString('Database', 'BackupPath', ChangeFileExt(Result.DatabasePath, '.fbk')); | |
finally | |
IniFile.Free; | |
end; | |
end; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses | |
SysUtils, IniFiles, Classes, ShellAPI, Windows, RegularExpressions, Dialogs, System.Threading, IBX.IBServices, IBX.IBUtils; | |
type | |
TDatabaseConfig = record | |
Server: string; | |
Port: string; | |
DatabasePath: string; | |
UserName: string; | |
Password: string; | |
BackupPath: string; | |
end; | |
// 0.pas | |
// 1.pas | |
function ValidarCaminhoBanco(const Config: TDatabaseConfig): Boolean; | |
begin | |
Result := True; // Assume que o caminho remoto é válido | |
if Config.Server = 'localhost' then | |
Result := FileExists(Config.DatabasePath); | |
end; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses | |
SysUtils, IniFiles, Classes, ShellAPI, Windows, RegularExpressions, Dialogs, System.Threading, IBX.IBServices, IBX.IBUtils; | |
type | |
TDatabaseConfig = record | |
Server: string; | |
Port: string; | |
DatabasePath: string; | |
UserName: string; | |
Password: string; | |
BackupPath: string; | |
end; | |
// 0.pas | |
// 1.pas | |
// 2.pas | |
procedure Log(const Msg: string); | |
var | |
LogFile: TextFile; | |
begin | |
AssignFile(LogFile, 'backup_log.txt'); | |
if FileExists('backup_log.txt') then | |
Append(LogFile) | |
else | |
Rewrite(LogFile); | |
try | |
WriteLn(LogFile, FormatDateTime('yyyy-mm-dd hh:nn:ss', Now) + ' - ' + Msg); | |
finally | |
CloseFile(LogFile); | |
end; | |
end; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses | |
SysUtils, IniFiles, Classes, ShellAPI, Windows, RegularExpressions, Dialogs, System.Threading, IBX.IBServices, IBX.IBUtils; | |
type | |
TDatabaseConfig = record | |
Server: string; | |
Port: string; | |
DatabasePath: string; | |
UserName: string; | |
Password: string; | |
BackupPath: string; | |
end; | |
// 0.pas | |
// 1.pas | |
// 2.pas | |
// 3.pas | |
function GetConfigFilePath: string; | |
var | |
IniFile: TIniFile; | |
ConfigFilePath: string; | |
begin | |
// Caminho padrão | |
Result := 'AppParams.ini'; | |
// Verificar parâmetros da linha de comando | |
if ParamCount > 0 then | |
begin | |
ConfigFilePath := ParamStr(1); | |
if FileExists(ConfigFilePath) then | |
begin | |
Result := ConfigFilePath; | |
Exit; | |
end | |
else | |
begin | |
ShowMessage('Arquivo de configuração especificado na linha de comando não encontrado: ' + ConfigFilePath); | |
end; | |
end; | |
// Verificar arquivo de configurações separado | |
if FileExists('settings.ini') then | |
begin | |
IniFile := TIniFile.Create('settings.ini'); | |
try | |
ConfigFilePath := IniFile.ReadString('Settings', 'ConfigFilePath', ''); | |
if FileExists(ConfigFilePath) then | |
Result := ConfigFilePath | |
else | |
ShowMessage('Arquivo de configuração especificado em settings.ini não encontrado: ' + ConfigFilePath); | |
finally | |
IniFile.Free; | |
end; | |
end; | |
end; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses | |
SysUtils, IniFiles, Classes, ShellAPI, Windows, RegularExpressions, Dialogs, System.Threading, IBX.IBServices, IBX.IBUtils; | |
type | |
TDatabaseConfig = record | |
Server: string; | |
Port: string; | |
DatabasePath: string; | |
UserName: string; | |
Password: string; | |
BackupPath: string; | |
end; | |
// 0.pas | |
// 1.pas | |
// 2.pas | |
// 3.pas | |
// 4.pas | |
procedure BackupDatabase; | |
var | |
ConfigFilePath: string; | |
Config: TDatabaseConfig; | |
IBBackupService1: TIBBackupService; | |
lOptions: TBackupOptions; | |
begin | |
try | |
ConfigFilePath := GetConfigFilePath; | |
if not FileExists(ConfigFilePath) then | |
begin | |
Log('Arquivo de configuração não encontrado: ' + ConfigFilePath); | |
ShowMessage('Arquivo de configuração não encontrado. Verifique o caminho e tente novamente.'); | |
Exit; | |
end; | |
Config := ExtractDatabaseConfig(ConfigFilePath); | |
if not ValidarCaminhoBanco(Config) then | |
begin | |
Log('Caminho do banco de dados inválido ou arquivo não encontrado.'); | |
TThread.Queue(nil, procedure | |
begin | |
ShowMessage('Caminho do banco de dados inválido ou arquivo não encontrado.'); | |
end); | |
Exit; | |
end; | |
// Tentar realizar o backup usando IBBackupService | |
IBBackupService1 := TIBBackupService.Create(nil); | |
try | |
IBBackupService1.Verbose := True; | |
IBBackupService1.LoginPrompt := False; | |
IBBackupService1.BackupFile.Clear(); | |
IBBackupService1.BackupFile.Add(Config.BackupPath); | |
IBBackupService1.DatabaseName := Config.DatabasePath; | |
IBBackupService1.ServerName := Config.Server + '/' + Config.Port; | |
IBBackupService1.Protocol := TIBProtocol.TCP; | |
IBBackupService1.Params.Add('user_name=' + Config.UserName); | |
IBBackupService1.Params.Add('password=' + Config.Password); | |
IBBackupService1.ServerType := 'IBServer'; | |
// Configurar opções de backup | |
lOptions := []; | |
// Adicione aqui as opções de backup conforme necessário | |
// Exemplo: Include(lOptions, NonTransportable); | |
IBBackupService1.Options := lOptions; | |
IBBackupService1.Active := True; | |
IBBackupService1.ServiceStart(); | |
while not IBBackupService1.Eof do | |
begin | |
Log(IBBackupService1.GetNextLine()); | |
end; | |
TThread.Queue(nil, procedure | |
begin | |
Log('Backup concluído com sucesso usando IBBackupService.'); | |
ShowMessage('Backup concluído com sucesso usando IBBackupService.'); | |
end); | |
except | |
on E: Exception do | |
begin | |
Log('Erro ao realizar backup com IBBackupService: ' + E.Message); | |
TThread.Queue(nil, procedure | |
begin | |
ShowMessage('Erro ao realizar backup com IBBackupService: ' + E.Message); | |
end); | |
end; | |
finally | |
IBBackupService1.Free; | |
end; | |
except | |
on E: Exception do | |
begin | |
Log('Erro ao iniciar backup: ' + E.Message); | |
ShowMessage('Erro ao iniciar backup: ' + E.Message); | |
end; | |
end; | |
end; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Database=usuario:[email protected]:3050:/var/lib/firebird/data/meu_banco.fdb | |
Database=usuario:senha@meu_servidor:3050:/var/lib/firebird/data/meu_banco.fdb | |
Database=192.168.1.100/3051:/var/lib/firebird/data/meu_banco.fdb | |
Database=meu_servidor/3051:/var/lib/firebird/data/meu_banco.fdb | |
Database=meu_servidor/3051:C:\databases\meu_banco.fdb | |
Database=meu_alias | |
Database=./databases/meu_banco.fdb | |
Database=.\databases\meu_banco.fdb | |
Database=C:\databases\meu_banco.fdb | |
Database=/var/lib/firebird/data/meu_banco.fdb |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses | |
ShellAPI, Windows, SysUtils, IBServices, Classes, DateUtils; | |
procedure ExecutarGbak(const Comando: string); | |
begin | |
ShellExecute(0, 'open', 'cmd.exe', PChar('/C ' + Comando), nil, SW_HIDE); | |
end; | |
function VerificarPermissoesPasta(const Pasta: string): Boolean; | |
var | |
SecurityDescriptor: PSecurityDescriptor; | |
SecurityAttributes: SECURITY_ATTRIBUTES; | |
Handle: THandle; | |
begin | |
Result := False; | |
SecurityDescriptor := nil; | |
try | |
SecurityAttributes.nLength := SizeOf(SECURITY_ATTRIBUTES); | |
SecurityAttributes.lpSecurityDescriptor := SecurityDescriptor; | |
SecurityAttributes.bInheritHandle := False; | |
Handle := CreateFile(PChar(Pasta), GENERIC_READ or GENERIC_WRITE, 0, @SecurityAttributes, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); | |
if Handle <> INVALID_HANDLE_VALUE then | |
begin | |
Result := True; | |
CloseHandle(Handle); | |
end; | |
except | |
// Tratar exceções conforme necessário | |
end; | |
end; | |
procedure CriarPastaTemporaria(out TempDir: string); | |
var | |
TempPath: array[0..MAX_PATH] of Char; | |
begin | |
GetTempPath(MAX_PATH, TempPath); | |
TempDir := IncludeTrailingPathDelimiter(TempPath) + 'MeuTempDir'; | |
if not DirectoryExists(TempDir) then | |
CreateDir(TempDir); | |
end; | |
procedure EnviarNotificacao(const Mensagem: string); | |
begin | |
// Implementar envio de notificação (e.g., e-mail, log, etc.) | |
Log(Mensagem); | |
end; | |
procedure LimparBackupsAntigos(const Pasta: string; Dias: Integer); | |
var | |
SR: TSearchRec; | |
FilePath: string; | |
begin | |
if FindFirst(IncludeTrailingPathDelimiter(Pasta) + '*.fbk', faAnyFile, SR) = 0 then | |
begin | |
repeat | |
FilePath := IncludeTrailingPathDelimiter(Pasta) + SR.Name; | |
if (SR.Attr and faDirectory = 0) and (DaysBetween(Now, FileDateToDateTime(SR.Time)) > Dias) then | |
begin | |
try | |
DeleteFile(FilePath); | |
Log('Backup antigo removido: ' + FilePath); | |
except | |
on E: Exception do | |
Log('Erro ao remover backup antigo: ' + FilePath + ' - ' + E.Message); | |
end; | |
end; | |
until FindNext(SR) <> 0; | |
FindClose(SR); | |
end; | |
end; | |
procedure BackupDatabase; | |
var | |
ConfigFilePath: string; | |
Config: TDatabaseConfig; | |
IBBackupService1: TIBBackupService; | |
lOptions: TBackupOptions; | |
TempDir, TempFileName: string; | |
ComandoGBak: string; | |
begin | |
try | |
ConfigFilePath := GetConfigFilePath; | |
if not FileExists(ConfigFilePath) then | |
begin | |
Log('Arquivo de configuração não encontrado: ' + ConfigFilePath); | |
ShowMessage('Arquivo de configuração não encontrado. Verifique o caminho e tente novamente.'); | |
Exit; | |
end; | |
Config := ExtractDatabaseConfig(ConfigFilePath); | |
if not ValidarCaminhoBanco(Config) then | |
begin | |
Log('Caminho do banco de dados inválido ou arquivo não encontrado.'); | |
TThread.Queue(nil, procedure | |
begin | |
ShowMessage('Caminho do banco de dados inválido ou arquivo não encontrado.'); | |
end); | |
Exit; | |
end; | |
// Verificar permissões da pasta de destino | |
if not VerificarPermissoesPasta(Config.BackupPath) then | |
begin | |
Log('Permissões insuficientes na pasta de destino.'); | |
TThread.Queue(nil, procedure | |
begin | |
ShowMessage('Permissões insuficientes na pasta de destino.'); | |
end); | |
Exit; | |
end; | |
// Criar uma pasta temporária | |
CriarPastaTemporaria(TempDir); | |
// Definir o nome do arquivo temporário na pasta temporária | |
TempFileName := IncludeTrailingPathDelimiter(TempDir) + 'backup_' + FormatDateTime('yyyymmdd_HHMMss', Now) + '.fbk'; | |
// Tentar realizar o backup usando IBBackupService | |
IBBackupService1 := TIBBackupService.Create(nil); | |
try | |
IBBackupService1.Verbose := True; | |
IBBackupService1.LoginPrompt := False; | |
IBBackupService1.BackupFile.Clear(); | |
IBBackupService1.BackupFile.Add(TempFileName); | |
IBBackupService1.DatabaseName := Config.DatabasePath; | |
IBBackupService1.ServerName := Config.Server + '/' + Config.Port; | |
IBBackupService1.Protocol := TIBProtocol.TCP; | |
IBBackupService1.Params.Add('user_name=' + Config.UserName); | |
IBBackupService1.Params.Add('password=' + Config.Password); | |
IBBackupService1.ServerType := 'IBServer'; | |
// Configurar opções de backup | |
lOptions := []; | |
// Adicione aqui as opções de backup conforme necessário | |
// Exemplo: Include(lOptions, NonTransportable); | |
IBBackupService1.Options := lOptions; | |
IBBackupService1.Active := True; | |
IBBackupService1.ServiceStart(); | |
while not IBBackupService1.Eof do | |
begin | |
Log(IBBackupService1.GetNextLine()); | |
end; | |
TThread.Queue(nil, procedure | |
begin | |
Log('Backup concluído com sucesso usando IBBackupService.'); | |
ShowMessage('Backup concluído com sucesso usando IBBackupService.'); | |
end); | |
except | |
on E: Exception do | |
begin | |
Log('Erro ao realizar backup com IBBackupService: ' + E.Message); | |
TThread.Queue(nil, procedure | |
begin | |
ShowMessage('Erro ao realizar backup com IBBackupService: ' + E.Message); | |
end); | |
end; | |
finally | |
IBBackupService1.Free; | |
end; | |
// Exemplo de comando para backup usando o arquivo temporário com GBAK | |
ComandoGBak := Format('gbak -b -user %s -password %s %s %s', [Config.UserName, Config.Password, Config.DatabasePath, TempFileName]); | |
try | |
ExecutarGbak(ComandoGBak); | |
// Mover o arquivo para a pasta de destino final | |
if not MoveFile(PChar(TempFileName), PChar(Config.BackupPath)) then | |
RaiseLastOSError; | |
Log('Backup realizado com sucesso.'); | |
EnviarNotificacao('Backup realizado com sucesso.'); | |
except | |
on E: Exception do | |
begin | |
Log('Erro ao executar o comando gbak: ' + E.Message); | |
EnviarNotificacao('Erro ao executar o comando gbak: ' + E.Message); | |
// Limpar a pasta temporária em caso de erro | |
try | |
RemoveDir(TempDir); | |
except | |
// Ignorar erros ao remover a pasta temporária | |
end; | |
raise; | |
end; | |
end; | |
// Limpar a pasta temporária | |
try | |
RemoveDir(TempDir); | |
except | |
// Ignorar erros ao remover a pasta temporária | |
end; | |
// Limpar backups antigos | |
LimparBackupsAntigos(ExtractFilePath(Config.BackupPath), 30); // Exemplo: limpar backups com mais de 30 dias | |
except | |
on E: Exception do | |
begin | |
Log('Erro ao iniciar backup: ' + E.Message); | |
ShowMessage('Erro ao iniciar backup: ' + E.Message); | |
EnviarNotificacao('Erro ao iniciar backup: ' + E.Message); | |
end; | |
end; | |
end; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment