File: MySQLConnection.pas

package info (click to toggle)
mysql-admin 1.0.20-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 31,248 kB
  • ctags: 23,912
  • sloc: pascal: 207,721; ansic: 34,574; cpp: 32,283; objc: 15,631; xml: 6,556; sh: 4,439; java: 2,123; php: 1,557; python: 1,225; sql: 1,069; makefile: 696
file content (1053 lines) | stat: -rw-r--r-- 33,893 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
unit MySQLConnection;

// Copyright (C) 2003, 2004 MySQL AB
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

interface

uses
  gnugettext, Windows, Messages, SysUtils, Classes, ComCtrls, ImgList,
  Controls, TntComCtrls, TntClasses, Forms, Contnrs,
  ExtCtrls, AuxFuncs, PNGImage, StdCtrls,
  SyncObjs, myx_public_interface, MyxError, Options;

const
  WM_Disconnected = WM_USER + 101;
  WM_Reconnected = WM_USER + 102;
  WM_DefaultSchemaChanged = WM_USER + 103;
  WM_SchemaListChanged = WM_USER + 104;

  CR_SERVER_GONE_ERROR = 2006;
  CR_SERVER_LOST = 2013;
  CR_CONN_HOST_ERROR = 2003;

type
  TFetchDataThread = class;

  DataBeingFetchedSet = set of 1..100;

  TThreadExecMethod = procedure(Sender: TObject) of object;

  IMySQLConnTransactionStatusChangeListener = interface
    procedure TransactionStatusChanged;
    procedure TransactionQueryExecuted(SQLCmd: WideString);
    procedure TransactionStarted;
  end;

  TMySQLConn = class(TObject)
  private
    FMySQL: Pointer;                             // Main MySQL server connection data.
    FDefaultSchema: WideString;
    FInTransaction: Boolean;
    FTransactionStatusChangeListeners: TList;
    FQuoteChar: WideString;
    FWorkList: TThreadList;
    FStatusBar: TTntStatusBar;

    function ShowConnectToInstanceForm(var User_connection: TMYX_USER_CONNECTION; var MySQL: Pointer;
      MySQLConnectionsOnly: Boolean; SelectSchemata: Boolean): Integer;
    function ConnectUsingUserConnection(Connection: WideString; var User_connection: TMYX_USER_CONNECTION;
      var FMySQL: Pointer; SelectSchemata: Boolean): Integer;
    function ConnectUsingCommandlineConnectionParams(var User_connection: TMYX_USER_CONNECTION; var FMySQL: Pointer;
      SelectSchemata: Boolean): Integer;
    function Connect(var FMySQL: Pointer; user_conn: TMYX_USER_CONNECTION; SelectSchemata: Boolean): Integer;
  protected
    procedure SetDefaultSchema(DefaultSchema: WideString);
    procedure SetInTransaction(InTransaction: Boolean);
    function GetQuoteChar: WideString;
    function GetFetchingData: Boolean;
  public
    MySQLMajorVersion,
    MySQLMinorVersion: Integer;
    user_connection: TMYX_USER_CONNECTION;
    ConnectionCaption: WideString;
    Params: TTntStringList;
    DoParameterSubstitution: Boolean;

    FCurrentDataThread: TFetchDataThread;        // Set by each thread as soon as it starts working. Access is serialized
                                                 // via the critical section.

    FetchDataThreadCriticalSection: TCriticalSection;
    FetchDataMultiReadSync: TMultiReadExclusiveWriteSynchronizer;

    QueryHookMultiReadSync: TMultiReadExclusiveWriteSynchronizer;
    QueryHookSQL: WideString;

    DataBeingFetched: DataBeingFetchedSet;

    Connected: Boolean;
    ConnectedToLocalhost: Boolean;

    constructor Create(StatusBar: TTntStatusBar);
    destructor Destroy; override;

    procedure ClearWorkList;
    procedure RefreshConnectionCaption;
    procedure CheckConnectionStatusChange(SQLCmd: WideString);
    procedure TransactionQueryExecuted;
    function ConnectToServer(AutoConnect: Boolean; MySQLConnectionsOnly: Boolean = True; SelectSchemata:
      Boolean = False): Integer;
    function Reconnect: Boolean;
    procedure Disconnect;
    procedure FetchData(KindOfData: Integer; FetchMethod: TThreadExecMethod; RefreshMethod: TThreadExecMethod;
      Target: TObject; StatusBarText: WideString; AllowParallelExecution: Boolean = False;
      AllowDuplicatedKindOfData: Boolean = False; ControlThread: TThread = nil);
    procedure StopCurrentThread(Timeout: Integer);

    function ExecuteDirect(SQLCmd: WideString; DisplayErrorDialog: Boolean = True): Boolean;

    procedure SchemaListChanged;

    procedure AddTransactionStatusListener(Listener: IMySQLConnTransactionStatusChangeListener);
    procedure RemoveTransactionStatusListener(Listener: IMySQLConnTransactionStatusChangeListener);

    property DefaultSchema: WideString read FDefaultSchema write SetDefaultSchema;
    property InTransaction: Boolean read FInTransaction write SetInTransaction;
    property MySQL: Pointer read FMySQL; 
    property QuoteChar: WideString read GetQuoteChar;
    property FetchingData: Boolean read GetFetchingData;
  end;

  TFetchDataThread = class(TThread)
  private
    FConnection: TMySQLConn;
    ErrorMsg: WideString;
    FetchMethod: TThreadExecMethod;
    RefreshMethod: TThreadExecMethod;
    SynchronizedMethod: TThreadExecMethod;
    KindOfData: Integer;
    FTarget: TObject;
    FStatusBarText: WideString;

    AllowParallelExecution: Boolean;
  protected
    procedure Execute; override;
    procedure SetStatusBar(StatusBarText: WideString);
  public
    constructor Create(AMySQLConn: TMySQLConn; AKindOfData: Integer; AFetchMethod: TThreadExecMethod;
      ARefreshMethod: TThreadExecMethod; ATarget: TObject; AStatusBarText: WideString; AAllowParallelExecution: Boolean);
    destructor Destroy; override;
    procedure ReleaseCriticalSection;
    procedure UpdateStatusBar;
    procedure ShowError;
    procedure ExecuteSynchronized(SynchronizedMethod: TThreadExecMethod);
    procedure ExecuteSynchronizedMethod;

    property Connection: TMySQLConn read FConnection;
    property Target: TObject read FTarget;
    property StatusBarText: WideString write SetStatusBar;
  end;

const
  //KindOfData
  KindOfData_CatalogSchema = 1;
  KindOfData_UserNames = 2;
  KindOfData_ProcessList = 3;
  KindOfData_SchemaTables = 4;
  KindOfData_StatusVars = 5;
  KindOfData_ServerVars = 6;
  KindOfData_UserData = 7;
  KindOfData_SchemaTableStatus = 8;
  KindOfData_TableAction = 9;
  KindOfData_SchemaIndices = 10;

//----------------------------------------------------------------------------------------------------------------------

implementation

uses
  ConnectToInstance;

//----------------------------------------------------------------------------------------------------------------------

constructor TMySQLConn.Create(StatusBar: TTntStatusBar);

begin
  // TODO: DLL Version check still missing
  inherited Create;

  FStatusBar := StatusBar;

  FWorkList := TThreadList.Create;
  FMySQL := nil;
  user_connection := nil;
  FTransactionStatusChangeListeners := nil;

  FDefaultSchema := '';

  Connected := False;
  ConnectedToLocalhost := False;

  //Initialize components for thread handling
  FetchDataThreadCriticalSection := TCriticalSection.Create;
  FetchDataMultiReadSync := TMultiReadExclusiveWriteSynchronizer.Create;
  DataBeingFetched := [];

  Params := TTntStringList.Create;
  DoParameterSubstitution := False;

  QueryHookMultiReadSync := TMultiReadExclusiveWriteSynchronizer.Create;
end;

//----------------------------------------------------------------------------------------------------------------------

destructor TMySQLConn.Destroy;

begin
  ClearWorkList;
  FWorkList.Free;

  FetchDataMultiReadSync.Free;
  FetchDataThreadCriticalSection.Free;

  QueryHookMultiReadSync.Free;

  if (user_connection <> nil) then
    user_connection.Free;

  Params.Free;

  // Close connection and free memory for MySQL struct
  myx_mysql_close(FMySQL);

  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.ClearWorkList;

// Goes through the work list and tells all waiting threads to terminate. Before that however the current thread must
// be stopped. It is given a timeout of 5 seconds to finish its work otherwise it is killed.

var
  I: Integer;

begin
  with FWorkList.LockList do
  try
    for I := 0 to Count - 1 do
      TFetchDataThread(Items[I]).Terminate;

    // Now that all threads are marked to terminate they will not start any work but immediately return
    // as soon as the fetch lock is free.
    // Now finish the currently active thread if there is one.
    if Assigned(FCurrentDataThread) then
    begin
      FCurrentDataThread.Terminate;

      // Wait 2 seconds and kill the thread if it did not stop working within that time.
      if WaitForSingleObject(FCurrentDataThread.Handle, 2000) = WAIT_TIMEOUT then
        TerminateThread(FCurrentDataThread.Handle, 999);
      FetchDataThreadCriticalSection.Release;
      FreeAndNil(FCurrentDataThread);
    end;
  finally
    FWorkList.UnlockList;
  end;

  repeat
    Sleep(100);
    with FWorkList.LockList do
    try
      I := Count;
    finally
      FWorkList.UnlockList;
    end;
  until I = 0;
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.ConnectToServer(AutoConnect: Boolean; MySQLConnectionsOnly: Boolean = True;
  SelectSchemata: Boolean = False): Integer;
  
begin
  //If AutoConnect and a connection was specified
  if (AutoConnect) and (MYXCommonOptions.ConnectionToUse <> '') then
    Result := ConnectUsingUserConnection(MYXCommonOptions.ConnectionToUse,
      User_connection,
      FMySQL, SelectSchemata)
  //If AutoConnect and username was specified
  else
    if (AutoConnect) and (MYXCommonOptions.ConnectionUsername <> '') then
      Result := ConnectUsingCommandlineConnectionParams(User_connection,
        FMySQL, SelectSchemata)
    else
      Result := ShowConnectToInstanceForm(User_connection, FMySQL, MySQLConnectionsOnly, SelectSchemata);

  if (Result = 1) then
  begin
    MySQLMajorVersion := myx_get_mysql_major_version(FMySQL);
    MySQLMinorVersion := myx_get_mysql_minor_version(FMySQL);

    RefreshConnectionCaption;

    Result := 1;

    Connected := True;
    ConnectedToLocalhost := (myx_is_localhost(user_connection.hostname) = 1);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.ShowConnectToInstanceForm(var User_connection: TMYX_USER_CONNECTION; var MySQL: Pointer;
  MySQLConnectionsOnly: Boolean; SelectSchemata: Boolean): Integer;

var
  ConnectToInstanceForm: TConnectToInstanceForm;
  ModalRes: Integer;

begin
  ConnectToInstanceForm := TConnectToInstanceForm.Create(nil,
    MySQLConnectionsOnly, SelectSchemata);
  try
    ModalRes := ConnectToInstanceForm.ShowModal;
    if (ModalRes = mrOK) then
    begin
      //Initialize Variables
      User_connection := TMYX_USER_CONNECTION.create(ConnectToInstanceForm.User_Connection.get_record_pointer);
      MySQL := ConnectToInstanceForm.PMySQL;
      DefaultSchema := myx_get_default_schema(FMySQL);

      Result := 1;
    end
    else
      if (ModalRes = mrAbort) then
        Result := -1
      else
        Result := 0;

  finally
    ConnectToInstanceForm.Free;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.ConnectUsingUserConnection(Connection: WideString; var User_connection: TMYX_USER_CONNECTION;
  var FMySQL: Pointer; SelectSchemata: Boolean): Integer;

var
  user_conns: PMYX_USER_CONNECTIONS;
  stored_conns: TMYX_USER_CONNECTIONS;
  user_conn: TMYX_USER_CONNECTION;
  error: MYX_LIB_ERROR;
  i: Integer;
  
begin
  Result := -1;

  //Get connection
  //Fetch connections from library
  user_conns := myx_load_user_connections(
    MYXCommonOptions.UserDataDir + 'mysqlx_user_connections.xml', @error);
  if (error <> MYX_NO_ERROR) then
    raise EMyxCommonLibraryError.Create(_('Error while loading stored connections.'),
      Ord(error), MYXCommonOptions.UserDataDir + 'mysqlx_user_connections.xml');

  try
    stored_conns := TMYX_USER_CONNECTIONS.create(user_conns);
    try
      user_conn := nil;
      for i := 0 to stored_conns.user_connections.Count - 1 do
      begin
        if (CompareText(stored_conns.user_connections[i].connection_name,
          MYXCommonOptions.ConnectionToUse) = 0) then
        begin
          user_conn := stored_conns.user_connections[i];
          break;
        end;
      end;

      //If the connection is found, connect
      if (user_conn <> nil) then
      begin
        //Copy connection
        User_connection := TMYX_USER_CONNECTION.Create(user_conn.get_record_pointer);

        Result := Connect(FMySQL, User_connection, SelectSchemata);
      end
      else
        ShowModalDialog(Application.Title + ' - ' + _('Connection not found'),
          Format(_('The connection %s cannot be found in the list of stored connections.'),
          [MYXCommonOptions.ConnectionToUse]), myx_mtError, _('OK'));
    finally
      stored_conns.Free;
    end;
  finally
    myx_free_user_connections(user_conns);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.ConnectUsingCommandlineConnectionParams(var User_connection: TMYX_USER_CONNECTION;
  var FMySQL: Pointer; SelectSchemata: Boolean): Integer;
  
begin
  //Create new connection form command line parameters
  User_connection := TMYX_USER_CONNECTION.Create(
    '',
    MYXCommonOptions.ConnectionUsername,
    MYXCommonOptions.ConnectionPassword,
    MYXCommonOptions.ConnectionHost,
    StrToIntDef(MYXCommonOptions.ConnectionPort, 3306),
    MYXCommonOptions.ConnectionSchema,
    '', '', MYX_MYSQL_CONN, MYX_FAVORITE_USER_CONNECTION);

  Result := Connect(FMySQL, User_connection, SelectSchemata);
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.Connect(var FMySQL: Pointer; user_conn: TMYX_USER_CONNECTION; SelectSchemata: Boolean): Integer;

var
  ConnectionResult: Integer;
  
begin
  //Initialize FMySQL
  FMySQL := myx_mysql_init();
  if (FMySQL = nil) then
  begin
    ShowModalDialog(Application.Title + ' ' + _('Error'),
      _('Error while allocating memory for MySQL Struct.'),
      myx_mtError, 'OK');

    Result := -1;
    Exit;
  end;

  //Connect to instance
  ConnectionResult := myx_connect_to_instance(
    user_conn.get_record_pointer,
    FMySQL);
  if (ConnectionResult = 0) then
  begin
    if (SelectSchemata) and (user_conn.schema <> '') then
    begin
      ConnectionResult := myx_use_schema(FMySQL, user_conn.schema);
      if (ConnectionResult <> 0) then
      begin
        ShowModalDialog(Application.Title + ' ' + _('Error'),
          Format(_('The schema %s cannot be selected.'),
          [user_conn.schema]),
          myx_mtError, 'OK');

        Result := -1;
        Exit;
      end;

      DefaultSchema := myx_get_default_schema(FMySQL);

    end;

    Result := 1;
  end
  else
  begin
    ShowModalDialog(Application.Title + ' ' + _('Error'),
      _('Could not connect to the specified host.') + ' ' + #13#10 + #13#10 +
      Format(_('MySQL Error Number %d' + #13#10 + '%s'),
      [myx_mysql_errno(FMySQL),
      myx_mysql_error(FMySQL)]),
        myx_mtError, 'OK');

    Result := -1;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.RefreshConnectionCaption;

begin
  if (User_Connection <> nil) then
  begin
    ConnectionCaption := User_Connection.username + '@' + User_Connection.hostname + ':' + IntToStr(User_Connection.port);
    if FDefaultSchema <> '' then
      ConnectionCaption := ConnectionCaption + ' / ' + FDefaultSchema;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

type
  TCastThread = class(TThread);
  
procedure TMySQLConn.FetchData(KindOfData: Integer; FetchMethod: TThreadExecMethod; RefreshMethod: TThreadExecMethod;
  Target: TObject; StatusBarText: WideString; AllowParallelExecution: Boolean; AllowDuplicatedKindOfData: Boolean;
  ControlThread: TThread);

// This method starts retrival of data by creating a separate thread and using the provided fetch and refresh methods.
// KindOfData determines what must be retrieved and is used in conjunction with AllowDuplicateKindOfData to allow or
// deny certain data retrieval actions.
// ControlThread has a special meaning as it is used to cancel long lasting operations. If it is assigned this method
// waits for the background to return unless the control thread gets terminated. In this case the data thread
// is killed and this method immediately returns to the caller.

var
  WaitResult: Cardinal;
  Thread: TFetchDataThread;
  
begin
  if (not (KindOfData in DataBeingFetched)) or
    (AllowDuplicatedKindOfData) then
  begin
    //Add KindOfData to DataBeingFetched Set
    if (not (KindOfData in DataBeingFetched)) then
      DataBeingFetched := DataBeingFetched + [KindOfData];
    try
      // Create a new thread.
      Thread := TFetchDataThread.Create(self, KindOfData, FetchMethod, RefreshMethod, Target, StatusBarText,
        AllowParallelExecution);
      FWorkList.Add(Thread);
      try
        // Thread will be freed after execution if no control thread is given.
        if ControlThread = nil then
          Thread.FreeOnTerminate := True;

        Thread.Resume;

        if Assigned(ControlThread) then
        begin
          // Wait for the data thread to finish but don't deadlock. Instead poll the thread until it is finished
          // or the control thread is terminated.
          WaitResult := WAIT_OBJECT_0;
          while not TCastThread(ControlThread).Terminated do
          begin
            WaitResult := WaitForSingleObject(Thread.Handle, 100);
            if WaitResult = WAIT_OBJECT_0 then
              Break;
          end;
          // Kill the fetch thread if the control thread has been told to finish but the fetch thread is still working.
          if WaitResult = WAIT_TIMEOUT then
          begin
            TerminateThread(Thread.Handle, 999);
            FetchDataThreadCriticalSection.Release;

            // Close the connection if we have to kill the last query.
            Reconnect;
           end;
          Thread.Free;
        end;
      except
        FWorkList.Remove(Thread);
        Thread.Free;

        raise;
      end;
    except
      DataBeingFetched := DataBeingFetched - [KindOfData];

      raise;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.StopCurrentThread(Timeout: Integer);

begin
  if Assigned(FCurrentDataThread) then
  begin
    FCurrentDataThread.Terminate;
    if WaitForSingleObject(FCurrentDataThread.Handle, Timeout) = WAIT_TIMEOUT then
      TerminateThread(FCurrentDataThread.Handle, 999);
    DataBeingFetched := DataBeingFetched - [FCurrentDataThread.KindOfData];
    FreeAndNil(FCurrentDataThread);
    FetchDataThreadCriticalSection.Release;
    if Assigned(FStatusBar) then
    begin
      FStatusBar.Panels[1].Text := '';
      FStatusBar.Invalidate;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.Reconnect: Boolean;

var
  ConnectionResult: Integer;

begin
  Result := False;

  if (User_Connection = nil) then
    Exit;

  if (FMySQL <> nil) then
    Disconnect;

  FMySQL := myx_mysql_init();
  if (FMySQL = nil) then
    raise EMyxError.Create('Error while allocating memory for MySQL Struct.');

  ConnectionResult := myx_connect_to_instance(
    User_Connection.get_record_pointer,
    FMySQL);
  if (ConnectionResult <> 0) then
    Exit;

  Connected := True;
  MessageToAllForms(WM_Reconnected, 0, 0);

  Result := True;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.Disconnect;

begin
  //Close connection and free memory for MySQL struct
  myx_mysql_close(FMySQL);
  FMySQL := nil;

  Connected := False;
  MessageToAllForms(WM_Disconnected, 0, 0);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.CheckConnectionStatusChange(SQLCmd: WideString);

  //----------------------------------------------------------------------------

  function IsEqual(Keyword: PChar; S: PWideChar): Boolean;

  // Determines if the given string S is (case insensitively) the same as the
  // given keyword. The string might end with space chars.

  begin
    // We are comparing ASCII strings here so we can safely cast to char
    // for quick case conversion.
    while (Keyword^ <> #0) and (Upcase(Char(S^)) = Keyword^) do
    begin
      Inc(Keyword);
      Inc(S);
    end;
    Result := (Keyword^ = #0) and (S^ in [WideChar(#0), WideChar(' ')]);
  end;

  //----------------------------------------------------------------------------

var
  Head: PWideChar;
  FoundTransactionCommand: Boolean;

begin
  // Catch transaction status change.
  Head := PWideChar(SQLCmd);
  while Head^ = ' ' do
    Inc(Head);

  // Examine first non-space letter for a quick decision.
  FoundTransactionCommand := False;
  case Head^ of
    'S', 's':
      if IsEqual('START TRANSACTION', Head) then
      begin
        InTransaction := True;
        FoundTransactionCommand := True;
      end;
    'C', 'c':
      if IsEqual('COMMIT', Head) then
      begin
        InTransaction := False;
        FoundTransactionCommand := True;
      end;
    'R', 'r':
      if IsEqual('ROLLBACK', Head) then
      begin
        InTransaction := False;
        FoundTransactionCommand := True;
      end;
  end;

  // When in transaction, check if the executed command auto-commits the Trx
  if not FoundTransactionCommand and InTransaction then
    InTransaction := (myx_check_whether_commits_transaction(FMySQL, SQLCmd) = 0);
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.ExecuteDirect(SQLCmd: WideString; DisplayErrorDialog: Boolean): Boolean;

var
  ErrorCode: MYX_LIB_ERROR;
  MySQLErrorNr: Integer;

begin
  FetchDataThreadCriticalSection.Acquire;
  try
    ExecuteDirect := False;
    try
      myx_query_execute_direct(FMySQL, SQLCmd,
        @ErrorCode);

      if (ErrorCode = MYX_NO_ERROR) then
      begin
        ExecuteDirect := True;

        //Check if command causes a transaction state change
        CheckConnectionStatusChange(SQLCmd);
      end
      else
      begin
        MySQLErrorNr := myx_mysql_errno(FMySQL);

        if (MySQLErrorNr = CR_SERVER_GONE_ERROR) or
          (MySQLErrorNr = CR_SERVER_LOST) or
          (MySQLErrorNr = CR_CONN_HOST_ERROR) then
        begin
          Disconnect;
        end;

        if (DisplayErrorDialog) then
          ShowModalDialog('Execution Error',
            'Error while executing query.' + #13#10#13#10 +
            SQLCmd + #13#10#13#10 +
            'MySQL Error Number ' + IntToStr(MySQLErrorNr) + #13#10 +
            myx_mysql_error(FMySQL),
            myx_mtError, 'OK');
      end;
    except
      on x: Exception do
        if (DisplayErrorDialog) then
          ShowModalDialog('Execution Error',
            'The following error occured while executing the query.' + #13#10#13#10 +
            SQLCmd + #13#10#13#10 +
            x.Message, myx_mtError, 'OK');
    end;
  finally
    FetchDataThreadCriticalSection.Release;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.SetDefaultSchema(DefaultSchema: WideString);

var
  error: Integer;

begin
  if FMySQL <> nil then
  begin
    if DefaultSchema <> '' then
    begin
      error := myx_use_schema(FMySQL, DefaultSchema);
      if (error = 0) then
        FDefaultSchema := myx_get_default_schema(FMySQL)
      else
        raise EMyxSQLError.Create(Format(
          _('The default schema cannot be changed to %s'), [DefaultSchema]),
          myx_mysql_errno(FMySQL), myx_mysql_error(FMySQL));
    end
    else
      FDefaultSchema := '';

    User_Connection.schema := DefaultSchema;

    RefreshConnectionCaption;

    MessageToAllForms(WM_DefaultSchemaChanged, 0, 0);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.SchemaListChanged;

begin
  MessageToAllForms(WM_SchemaListChanged, 0, 0);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure MySQLQueryPostHook(mysql: Pointer; cdata: Pointer; query: PChar; length: Integer); cdecl;

var
  PSender: TMySQLConn;

begin
  PSender := cdata;

  PSender.QueryHookMultiReadSync.BeginWrite;
  try
    PSender.QueryHookSQL := UTF8Decode(query);
  finally
    PSender.QueryHookMultiReadSync.EndWrite;
  end;

  TThread.Synchronize(nil, PSender.TransactionQueryExecuted);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.SetInTransaction(InTransaction: Boolean);

var
  I: Integer;
  TransactionStarted: Boolean;

begin
  if FInTransaction <> InTransaction then
  begin
    TransactionStarted := ((Not (FInTransaction)) and (InTransaction));

    FInTransaction := InTransaction;

    if Assigned(FTransactionStatusChangeListeners) then
      for I := 0 to FTransactionStatusChangeListeners.Count - 1 do
      begin
        if (TransactionStarted) then
          IMySQLConnTransactionStatusChangeListener(FTransactionStatusChangeListeners[I]).TransactionStarted;
          
        IMySQLConnTransactionStatusChangeListener(FTransactionStatusChangeListeners[I]).TransactionStatusChanged;
      end;

    if FInTransaction then
      myx_mysql_set_query_hooks(FMySQL, nil, @MySQLQueryPostHook, Self)
    else
      myx_mysql_set_query_hooks(FMySQL, nil, nil, nil);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.GetQuoteChar: WideString;

begin
  if (FQuoteChar='') then
    FQuoteChar := Chr(myx_get_mysql_quote_char(FMySQL, 0));

  Result := FQuoteChar;
end;

//----------------------------------------------------------------------------------------------------------------------

function TMySQLConn.GetFetchingData: Boolean;

begin
  Result := (FCurrentDataThread<>nil);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.AddTransactionStatusListener(Listener: IMySQLConnTransactionStatusChangeListener);

begin
  if FTransactionStatusChangeListeners = nil then
    FTransactionStatusChangeListeners := TList.Create;
  if FTransactionStatusChangeListeners.IndexOf(Pointer(Listener)) = -1 then
    FTransactionStatusChangeListeners.Add(Pointer(Listener));
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.RemoveTransactionStatusListener(Listener: IMySQLConnTransactionStatusChangeListener);

begin
  if FTransactionStatusChangeListeners <> nil then
  begin
    FTransactionStatusChangeListeners.Remove(Pointer(Listener));

    if FTransactionStatusChangeListeners.Count = 0 then
    begin
      FTransactionStatusChangeListeners.Free;
      FTransactionStatusChangeListeners := nil;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TMySQLConn.TransactionQueryExecuted;

var
  I: Integer;

begin
  QueryHookMultiReadSync.BeginRead;
  try
    if Assigned(FTransactionStatusChangeListeners) then
      for I := 0 to FTransactionStatusChangeListeners.Count - 1 do
        IMySQLConnTransactionStatusChangeListener(
          FTransactionStatusChangeListeners[I]).TransactionQueryExecuted(QueryHookSQL);
  finally
    QueryHookMultiReadSync.EndRead;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

constructor TFetchDataThread.Create(AMySQLConn: TMySQLConn; AKindOfData: Integer; AFetchMethod: TThreadExecMethod;
  ARefreshMethod: TThreadExecMethod; ATarget: TObject; AStatusBarText: WideString; AAllowParallelExecution: Boolean);

begin
  inherited Create(True);

  FConnection := AMySQLConn;
  self.KindOfData := AKindOfData;
  self.FetchMethod := AFetchMethod;
  self.RefreshMethod := ARefreshMethod;
  FTarget := ATarget;
  self.StatusBarText := AStatusBarText;
  SynchronizedMethod := nil;
  AllowParallelExecution := AAllowParallelExecution;
end;

//----------------------------------------------------------------------------------------------------------------------

destructor TFetchDataThread.Destroy;

begin
  StatusBarText := '';
  Synchronize(UpdateStatusBar);

  inherited Destroy;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TFetchDataThread.Execute;

begin
  if (not (AllowParallelExecution)) then
    FConnection.FetchDataThreadCriticalSection.Acquire;
  try
    try
      with FConnection.FWorkList.LockList do
      try
        Remove(Self);
      finally
        FConnection.FWorkList.UnlockList;
      end;

      if not Terminated then
      begin
        FConnection.FCurrentDataThread := Self;

        if (FStatusBarText <> '') then
          Synchronize(UpdateStatusBar);

        if (Assigned(FetchMethod)) then
          FetchMethod(self);

        if (Assigned(RefreshMethod)) then
          ExecuteSynchronized(RefreshMethod);
      end;
    except
      on x: EMyxSQLError do
      begin
        if (x.ErrorNr = CR_SERVER_GONE_ERROR) or
          (x.ErrorNr = CR_SERVER_LOST) or
          (x.ErrorNr = CR_CONN_HOST_ERROR) then
        begin
          FConnection.Disconnect;
        end;

        ErrorMsg := x.FormattedMessage;
        Synchronize(ShowError);
      end;
      on x: Exception do
      begin
        ErrorMsg := x.Message;
        Synchronize(ShowError);
      end;
    end;
  finally
    FConnection.FCurrentDataThread := nil;
    FConnection.DataBeingFetched := FConnection.DataBeingFetched - [KindOfData];
    if (not (AllowParallelExecution)) then
      FConnection.FetchDataThreadCriticalSection.Release;

    Synchronize(UpdateStatusBar);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TFetchDataThread.ReleaseCriticalSection;

begin
  FConnection.FetchDataThreadCriticalSection.Release;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TFetchDataThread.UpdateStatusBar;

begin
  if Assigned(FConnection.FStatusBar) then
  begin
    if FConnection.FStatusBar.Panels.Count > 1 then
    begin
      FConnection.FStatusBar.Panels[1].Text := FStatusBarText;
      FConnection.FStatusBar.Repaint;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TFetchDataThread.ShowError;

begin
  ShowModalDialog(Application.Title + ' ' + _('Error'), ErrorMsg,
    myx_mtError, _('OK'));
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TFetchDataThread.ExecuteSynchronized(SynchronizedMethod: TThreadExecMethod);

begin
  self.SynchronizedMethod := SynchronizedMethod;

  Synchronize(ExecuteSynchronizedMethod);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TFetchDataThread.ExecuteSynchronizedMethod;

begin
  if Assigned(SynchronizedMethod) then
    SynchronizedMethod(self);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TFetchDataThread.SetStatusBar(StatusBarText: WideString);

begin
  FStatusBarText := StatusBarText;

  UpdateStatusBar;
end;

//----------------------------------------------------------------------------------------------------------------------

end.