#1 2019-07-10 16:19:02

MC
Member
Registered: 2012-10-04
Posts: 21

SQLite3 LoadFromStream and SaveToStream

Hello,

I use these procedures in order to load/save an in memory SQLite3 database from/to an encrypted file with ECC.

Maybe it could be useful for someone...

uses SynSQLite3...

procedure SQLite3_SaveToStream(pcDB : TSQLite3DB; pcStream : TStream);
var
  vSize   : Int64;
  vMemory : Pointer;  
begin

  // Database must be opened before calling

  vMemory := nil;

  try //-> finally

    vMemory := sqlite3.serialize(pcDB, 'main', @vSize, 0);

    if not Assigned(vMemory) then
    begin
      raise Exception.Create('memory allocation error');        
    end;
    
    pcStream.WriteBuffer(vMemory^, vSize);

  finally

    if Assigned(vMemory) then
    begin
      sqlite3.free_(vMemory);
    end;

  end;
end;

procedure SQLite3_LoadFromStream(pcDB : TSQLite3DB; pcStream : TStream);
const
  SQLITE_DESERIALIZE_FREEONCLOSE = 1; // Call sqlite3_free() on close
  SQLITE_DESERIALIZE_RESIZEABLE  = 2; // Resize using sqlite3_realloc64()
  SQLITE_DESERIALIZE_READONLY    = 4; // Database is read-only
var
  vSize       : Int64;
  vMemory     : Pointer;
  vMemoryFree : Boolean;
  vFile       : TFileStream;
begin                                                                         

  // Database must be opened before calling

  vMemory     := nil;
  vMemoryFree := False;

  try //-> finally

    vSize := pcStream.Size;

    if (vSize <= 0) then
    begin
      raise Exception.Create('incorrect stream size');
    end;

    vMemory := sqlite3.malloc(vSize);

    if (vMemory = nil) then
    begin
      raise Exception.Create('memory allocation error'); 
    end;

    vMemoryFree := True;

    pcStream.ReadBuffer(vMemory^, vSize);

    vMemoryFree := False;

    if Integer
    (
      sqlite3.deserialize
      (
        pcDB,
        'main',
        vMemory,
        vSize,
        vSize,
        (SQLITE_DESERIALIZE_FREEONCLOSE or SQLITE_DESERIALIZE_RESIZEABLE),
      )
    ) 
    <> 
    0 
    then
    begin
      raise Exception.Create('deserialize error');     
    end;

  finally

    if (vMemoryFree = True) then
    begin
      if Assigned(vMemory) then
      begin
        sqlite3.free_(vMemory);
      end;
    end;
  end;
end;

Offline

Board footer

Powered by FluxBB