delphiutf-8stringstreamfiredactstream

How to load a TStringStream from database with DBConnection set to UTF-8 charset?


We are changing the database connection settings for our project from WIN1252 to UTF8. (FireDAC). It is a PostgreSQL database created with UTF-8 encoding.

There are some text fields that we load from stream due to their size. This was working before, but now only the first char of the text is loaded.

Here is the code we had before changing the database connection's charset:

procedure TfrmTeste.LoadSqlScript_old;
var
  _Stream: TStream;
begin
  _Stream := qry1.CreateBlobStream(
                  qry1.FieldByName('Script'),
                  bmRead
              );
  try
    FReportQry.Sql.LoadFromStream(_Stream);
  finally
    _Stream.Free;
  end;
end;

As I mentioned, the text loaded only contains the first character of the original text. I tried to load the text to a TStringStream in order to understand what's going on:

procedure TfrmTeste.LoadSqlScript_new;
var
  _StringStream: TStringStream;
  _Stream: TStream;
begin
  _StringStream := TStringStream.Create;
  try
    _Stream := qry1.CreateBlobStream(
                    qry1.FieldByName('Script'),
                    bmRead
                );
    try

      _StringStream.LoadFromStream(_Stream);
      _StringStream.SaveToFile('c:\tmp\test.sql');

      FReportQry.Sql.LoadFromStream(_StringStream);
    finally
      _Stream.Free;
    end;
  finally
    _StringStream.Free;
  end;
end;

Interestingly enough, the text file saved to disk has the full text. But the text loaded to TQuery.SQL only has the first character.

Delphi Rio 10.3.3 with FireDAC.


Solution

  • Thanks to Remy the code below works for my case:

      _Stream := _Qry.CreateBlobStream(_Qry.FieldByName('Script'), bmRead);
      _StrStream := TStringStream.Create;
      try
        _StrStream.LoadFromStream(_Stream);
        Query.Sql.LoadFromStream(_StrStream, TEncoding.Unicode);
      finally
        _Stream.Free;
        _StrStream.Free;
      end;