Visit our Sponsor   Visit our Sponsor
delphi3000.com - the free delphi knowledge platform
delphi3000.com - the free delphi knowledge platform
Have a look at your member-status

connecting people's knowledge


  - Recent ArticlesRSS feed for Recent Articles on delphi3000.com
  - List of All Articles
  - Top Viewed Articles
  - Articles (+Attachem.)
  - Articles Of Interest
  - Categories
  - Top Uploader
  - Search
  - Index

  - My Home
  - Submit an Article
  - My Articles
  - My Personal Data
  - My Bookmarks
  - Activities
  - Login/Logout

  - Sign Up
  - Why Sign Up
  - Newsletter

  - Press
  - Advertise

  - Contact
  - Feedback





Community
Borland
ClubeDelphi
Dr. Bob
UK-BUG
Delphi Meetings
Planeta Delphi







Startblatt.de






Share this article with friendsShare this article with friends
Rate this articleRate this article - to keep the quality of delphi3000.com !
Comment this article or read through previous comments (2)


Interbase Backup on the Fly in a threadGo to Kim Sandell's websiteFormat this article printer-friendly!Bookmark function is only available for registered users!
Make interbase database backups on the fly, in a background thread
Product:
Delphi 5.x (or higher)
Category:
Database-SQL
Skill Level:
Scoring:
Last Update:
07/18/2008
Search Keys:
delphi delphi3000 article borland vcl code-snippet Interbase database automated backup thread
Times Scored:
3
Visits:
6167
Uploader: Kim Sandell
Company: Celarius Oy
Reference: N/A
 
Question/Problem/Abstract:
In the Interbase Admin components there is a IBBackupService but is hard to use as it is. This component makes this alot easier, and also works in a thread.
Answer:



(*
  Interbase Backup Thread

  Author
    Kim Sandell
    Email: kim.sandell@celarius.com  

  Description
    A Thread that performs an backup of an interbase database on the fly.

  History
    23.09.2002  - Initial version

  Example of usage

    The example below assumes you have included the "IBBackupThread" unit
    in the uses clause, and that you have a button on a form.

    The example makes 10 fragments, each max 4 Megabytes. If the backup
    is larger, the last (10th fragment) will be bigger than 4 Megs.

    procedure TForm1.Button1Click(Sender: TObject);
    Var
       IBB: TIBBackupThread;
    begin
         IBB := NIL;
         Try
            IBB := TIBBackupThread.Create(True);
            IBB.Initialize;
            IBB.BackupPath := 'C:\Databases';
            IBB.DatabaseName := '127.0.0.1:C:\Databases\MyIBDB.GDB';
            IBB.DatabaseUsername := 'SYSDBA';
            IBB.DatabasePassword := 'masterkey';
            IBB.Fragments := 4;
            IBB.FragmentSizeK := 4096;
            IBB.Resume;
            While Not IBB.Terminated do
            Begin
                 SleepEx(1,True);
                 Application.ProcessMessages;
            End;
            IBB.WaitForAndSleep;
            If IBB.Success then
            Begin
                 MessageDlg('Backup OK',mtInformation,[mbOK],0);
                 ShowMessage( IBB.BackupLog.Text );
            End Else MessageDlg('Backup FAILED',mtError,[mbOK],0);
         Finally
            IBB.Free;
         End;
    end;
*)
unit IBBackupThread;

interface

uses
  Windows, Messages, SysUtils, Classes,
  IB, IBServices;

type
  TIBBackupThread = class(TThread)
  private
    { Private declarations }
  protected
    { Protected declarations }
    Function BackupDatabase: Boolean;
  public
    { Public declarations }
    BackupOptions         : TBackupOptions; // Backup Options
    BackupLog             : TStringList;    // A Stringlist with the results of the backup
    BackupPath            : String;         // Path on server
    DatabaseName          : String;         // Fully qualifyed name to db
    DatabaseUsername      : String;         // Username
    DatabasePassword      : String;         // Password
    Fragments             : Cardinal;       // How many backup files. 0 means 1 file.
    FragmentSizeK         : Cardinal;       // Max Size of a backup fragment in KByte
    Success               : Boolean;        // After operation, indicates Success or Fail

    Property Terminated;                    // Make the Terminated published

    { Methods }
    Procedure Initialize;
    Destructor Destroy; Override;
    Procedure Execute; Override;
    Procedure WaitForAndSleep;              // Special WaitFor that does not take 100% CPU
  published
    { Published declarations }
  end;

implementation

{ TIBBackupThread }

Procedure TIBBackupThread.Initialize;
begin
     { Create variables }
     BackupLog := TStringList.Create;
     { Initialize default values }
     BackupPath := '';
     DatabaseName := '';
     DatabaseUsername := 'SYSDBA';
     DatabasePassword := '';
     Fragments := 0;
     FragmentSizeK := 0;
     Success := False;
     { Default to no options }
     BackupOptions := [];
end;

destructor TIBBackupThread.Destroy;
begin
     Try
        { Free the result list }
        If Assigned(BackupLog) then BackupLog.Free;
     Finally
        inherited;
     End;
end;

procedure TIBBackupThread.WaitForAndSleep;
Var
   H : THandle;
   D : DWord;
begin
     { Get Handle }
     H := Handle;
     { Wait for it to terminate }
     Repeat
           D := WaitForSingleObject(H, 1);
           { System Slizes }
           SleepEx(1,True);
     Until (Terminated) OR ((DWAIT_TIMEOUT) AND (DWAIT_OBJECT_0));
end;

procedure TIBBackupThread.Execute;
begin
     Try
        { Do not free it on termination }
        FreeOnTerminate := False;
        { Set lower priority }
        Priority := tpLower;            // tpXXXXX variables
        Try
           Success := BackupDatabase;
        Finally
        End;
     Except
     End;
     { Signal the termination of the Thread }
     Terminate;
end;

function TIBBackupThread.BackupDatabase: Boolean;
Var
   IBBack   : TIBBackupService;
   SrvAddr  : String;
   DBPath   : String;
   BakPath  : String;
   BakName  : String;
   I        : Integer;

   { Leading Zero function }
   Function Lz( Value:Cardinal; Digits:Byte ):String;
   Begin
        Result := IntToStr(Value);
        While Length(Result)  Digits do
          Result := '0'+Result;
   End;

begin
     { Default Result }
     Result := False;
     Try
        { Clear log }
        BackupLog.Clear;
        { Initialize Values }
        IBBack := NIL;
        { Extract SrvAddr and DBPath from DatabaseName }
        BakPath := IncludeTrailingPathDelimiter( BackupPath );
        SrvAddr := DatabaseName;
        { Correct if Local machine }
        If Pos(':',SrvAddr)0 then
        Begin
             Delete( SrvAddr, Pos(':',SrvAddr), Length(SrvAddr) );
             DBPath := DatabaseName;
             Delete( DBPath, 1, Pos(':',DBPath) );
        End Else
        Begin
             { Must be localhost since Server Address is missing }
             SrvAddr := '127.0.0.1';
             DBPath := DatabaseName;
        End;
        { Make sure the Fragments & Size are is OK }
        If FragmentSizeK=0 then Fragments := 0;
        If Fragments999 then Fragments := 999;
        If Fragments=0 then FragmentSizeK:=0;
        Try
           { Create the Backup service component }
           IBBack := TIBBackupService.Create( NIL );
           IBBack.Protocol := TCP;
           IBBack.LoginPrompt := False;
           IBBack.Params.Values['user_name'] := DatabaseUsername;
           IBBack.Params.Values['password'] := DatabasePassword;
           IBBack.ServerName  := SrvAddr;
           IBBack.DatabaseName := DBPath;
           IBBack.Options := BackupOptions;
           IBBack.Active := True;
           Try
              IBBack.Verbose := True;
              { Add the Backup filenames }
              For I:=0 to Fragments do
              Begin
                   { Create the Backup filename }
                   BakName := ExtractFileName(DBPath);
                   Delete(BakName,Pos('.',BakName),Length(BakName));
                   BakName := IncludeTrailingPathDelimiter(BackupPath)+BakName;
                   { Check if we need to make a fragment file }
                   If I=0 then
                   Begin
                        BakName := BakName+'_'+FormatDateTime('YYYYMMDD_HHNNSS',Now)+'.gbk';
                        If (FragmentSizeK0) then BakName := BakName+' = '+IntToStr(FragmentSizeK*1024);
                   End Else
                   Begin
                        BakName := BakName+'_'+FormatDateTime('YYYYMMDD_HHNNSS',Now)+'.gbk_'+Lz(I,3);
                        If (FragmentSizeK0) then BakName := BakName+' = '+IntToStr(FragmentSizeK*1024);
                   End;
                   { Add the Bakup name to the Filelist }
                   IBBack.BackupFile.Add( BakName );
              End;
              { Start the Service }
              IBBack.ServiceStart;
              { Get the Resulting Report Lines }
              While NOT IBBack.Eof do
              Begin
                   BackupLog.Append( IBBack.GetNextLine );
                   Sleep(1);
              END;
           Finally
              { Turn the Backup service off }
              IBBack.Active := False;
           End;
           { Return results }
           Result := True;
        Finally
           If Assigned(IBBack) then
           Begin
                IBBack.Active := False;
                IBBack.Free;
           End;
        End;
     Except
        On E:Exception do ; // Log error here
     End;
end;

end.





Please rate this article!
Skill level:
BeginnerExpert

Useful:
No!Very!

Overall rating:
PoorExcellent



Comments to this article
Write a new comment
?
    anonymus (May 20 2004 9:50AM)

{ Leading Zero function }
   Function Lz( Value:Cardinal; Digits:Byte ):String;
   Begin
        Result := IntToStr(Value);
!!!???        While Length(Result)   End;
Respond

thx
    J M (Dec 6 2002 11:09AM)

dude ya helped me a lot much thx from me
Respond














 
Sign up to consume product discounts for Bronze memberships !

read more


  Visit our Sponsor

 

  Community Ad of
Hans Gulö
 
   














 







     
  Copyright © 2000 - 2007 delphi3000.com - All rights reserved. Terms of use. || Privacy
delphi3000.com is a service by bluestep.com IT-Services GmbH (Vienna)