Skip to content

Commit a48a722

Browse files
fix: hanging query tab and double execution of non-SELECT queries on MS SQL
Opening the result of a statement without result set executed it a second time, then raised an exception which silently killed the query thread. Only keep results which have rows, and finish the batch with an error if setting up results fails. Closes #2392
1 parent 363f829 commit a48a722

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎source/apphelpers.pas‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3209,7 +3209,15 @@ procedure TQueryThread.Execute;
32093209
end;
32103210
end;
32113211
FConnection.SetLockedByThread(nil);
3212-
Synchronize(AfterQuery);
3212+
try
3213+
Synchronize(AfterQuery);
3214+
except
3215+
// Synchronize re-raises here. Without BatchFinished, the tab would stay in running state forever.
3216+
on E:Exception do begin
3217+
FErrorMessage := E.Message;
3218+
ErrorAborted := True;
3219+
end;
3220+
end;
32133221
// Check if FAborted is set by the main thread, to avoid proceeding the loop in case
32143222
// FStopOnErrors is set to false
32153223
if FAborted or ErrorAborted then

‎source/dbconnection.pas‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3711,10 +3711,15 @@ procedure TMySQLConnection.Query(SQL: String; DoStoreResult: Boolean=False; LogC
37113711
end;
37123712

37133713
{$IFDEF HASMSSQL}
3714+
type
3715+
// Grants access to the protected Cursor, see TSqlSrvConnection.Query
3716+
TSQLQueryAccess = class(TSQLQuery);
3717+
37143718
procedure TSqlSrvConnection.Query(SQL: String; DoStoreResult: Boolean=False; LogCategory: TDBLogCategory=lcSQL);
37153719
var
37163720
TimerStart: QWord;
37173721
QueryResult: TSQLQuery;
3722+
HasRows: Boolean;
37183723
begin
37193724
inherited;
37203725

@@ -3729,8 +3734,18 @@ procedure TSqlSrvConnection.Query(SQL: String; DoStoreResult: Boolean=False; Log
37293734
QueryResult.SQL.Text := SQL;
37303735
QueryResult.Options := [sqoAutoApplyUpdates, sqoAutoCommit, sqoCancelUpdatesOnRefresh];
37313736
QueryResult.PacketRecords := 10000;
3737+
// Prepare explicitly, so the cursor survives ExecSQL and tells us whether a result set came back
3738+
QueryResult.Prepare;
37323739
QueryResult.ExecSQL;
37333740
Inc(FRowsAffected, QueryResult.RowsAffected);
3741+
HasRows := TSQLQueryAccess(QueryResult).Cursor.FSelectable;
3742+
QueryResult.UnPrepare;
3743+
if not HasRows then begin
3744+
// Opening a statement without result set would execute it a second time, and then raise
3745+
// "Cannot open a non-select statement". See issue #2392
3746+
FLastRawResults.Remove(QueryResult);
3747+
FreeAndNil(QueryResult);
3748+
end;
37343749
FLastQueryDuration := GetTickCount64 - TimerStart;
37353750
FLastQueryNetworkDuration := 0;
37363751

0 commit comments

Comments
 (0)