Skip to content

Commit 6321260

Browse files
committed
Issue #515: Handle encoding errors in apphelpers.ReadTextfileChunk according to how Delphi 10.3 raises exceptions. And probably fix the issue by increasing the new chunk size by 1M instead of only 4B.
1 parent 141c348 commit 6321260

File tree

2 files changed

+19
-17
lines changed

2 files changed

+19
-17
lines changed

source/apphelpers.pas

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1338,7 +1338,7 @@ function DetectEncoding(Stream: TStream): TEncoding;
13381338

13391339
function ReadTextfileChunk(Stream: TFileStream; Encoding: TEncoding; ChunkSize: Int64 = 0): String;
13401340
const
1341-
BufferPadding = 4;
1341+
BufferPadding = SIZE_MB;
13421342
var
13431343
DataLeft, StartPosition: Int64;
13441344
LBuffer: TBytes;
@@ -1356,24 +1356,22 @@ function ReadTextfileChunk(Stream: TFileStream; Encoding: TEncoding; ChunkSize:
13561356
ChunkSize := DataLeft;
13571357

13581358
i := 0;
1359-
while Length(LBuffer) = 0 do begin
1360-
SetLength(LBuffer, ChunkSize);
1361-
Stream.ReadBuffer(Pointer(LBuffer)^, ChunkSize);
1362-
LBuffer := Encoding.Convert(Encoding, TEncoding.Unicode, LBuffer);
1363-
if Length(LBuffer) = 0 then begin
1364-
// Now, TEncoding.Convert returns an empty TByte array in files with russion characters
1365-
// See http://www.heidisql.com/forum.php?t=13044
1366-
// Re-read the whole chunk + some more bytes
1367-
// See: Classes.TStreamReader.FillBuffer
1368-
// See: https://forums.embarcadero.com/message.jspa?messageID=368526
1369-
MainForm.LogSQL(f_('End of file block was cut within some multibyte character, at position %s. Increasing chunk size and retry reading...', [FormatNumber(Stream.Position)]), lcError);
1370-
Stream.Position := StartPosition;
1371-
Inc(ChunkSize, BufferPadding);
1372-
end else // Success, exit loop
1373-
Break;
1359+
while True do begin
13741360
Inc(i);
1375-
if i=10 then // Give up
1361+
try
1362+
SetLength(LBuffer, ChunkSize);
1363+
Stream.ReadBuffer(Pointer(LBuffer)^, ChunkSize);
1364+
LBuffer := Encoding.Convert(Encoding, TEncoding.Unicode, LBuffer);
1365+
// Success, exit loop
13761366
Break;
1367+
except
1368+
on E:EEncodingError do begin
1369+
if i=10 then // Give up
1370+
Raise;
1371+
Stream.Position := StartPosition;
1372+
Inc(ChunkSize, BufferPadding);
1373+
end;
1374+
end;
13771375
end;
13781376

13791377
Result := TEncoding.Unicode.GetString(LBuffer);

source/main.pas

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3816,6 +3816,10 @@ procedure TMainForm.RunQueryFile(FileName: String; Encoding: TEncoding);
38163816
f_('Notice: You can disable the "%s" option to ignore such errors', [actQueryStopOnErrors.Caption])
38173817
);
38183818
end;
3819+
on E:EEncodingError do begin
3820+
StopProgress;
3821+
ErrorDialog(E.Message);
3822+
end;
38193823
end;
38203824
end;
38213825

0 commit comments

Comments
 (0)