File: idemcindexer.pas

package info (click to toggle)
lazarus 4.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 275,760 kB
  • sloc: pascal: 2,341,904; xml: 509,420; makefile: 348,726; cpp: 93,608; sh: 3,387; java: 609; perl: 297; sql: 222; ansic: 137
file content (1074 lines) | stat: -rw-r--r-- 29,862 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
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
unit idemcindexer;

{$mode ObjFPC}{$H+}
{$modeswitch advancedrecords}

interface

uses
  Classes, SysUtils, Types, DB, SQLDB, MySQL80Conn, fpJSON;

Const
  DefaultMCMySQLPort   = 9306;
  DefaultMCHTTPPort    = 9308;
  DefaultMCBinaryPort  = 9312;
  DefaultMCIndexName   = 'sources';
  DefaultMCMinInfixLen = 3;

Type
  EManticoreSearch = Class(Exception)
    ManticoreCommand : String;
  end;

  TMCIndexOption = (ioRecurse,ioStoreRelativeNames,ioAllFiles);
  TMCIndexOptions = set of TMCIndexOption;

  TMCTransport = (mctNone,mctMysql,mctHttp);
  TMCMySQLClientVersion = (mcvNone,mcv57,mcv80);

  TMCLogkind = (mlkError,mlkInfo,mlkDebug,mlkProgress);
  TMCLogEvent = Procedure(Sender : TObject; aKind : TMCLogKind; const aMessage : String) of object;
  TIndexProgressEvent = Procedure(Sender : TObject; const aFileName : String; var aContinue : Boolean) of object;

  { TMCSearchResult }

  TMCSearchResult = record
    ID : Int64;
    Tree : string;
    FileName : string;
    LineNo : Integer;
    Content : String;
    Weight : Integer;
    Function Description(aFull: Boolean = False) : string;
  end;
  PMCSearchResult = ^TMCSearchResult;
  TMCSearchResultArray = Array of TMCSearchResult;
  TMCSearchResultCallBack = Procedure (Sender : TObject; const aResult : TMCSearchResult; aData : Pointer; var aContinue : Boolean) of object;

  { TMCToArrayConverter }

  TMCToArrayConverter = class
    Results : TMCSearchResultArray;
    Count : Cardinal;
    FGrowDelta : Cardinal;
    constructor Create(aGrowDelta : Cardinal);
    Procedure DoAddToResult(Sender : TObject; const aResult : TMCSearchResult; aData : Pointer; var aContinue : Boolean);
  end;


  { TManticoreSearchSources }

  TManticoreSearchSources = class(TComponent)
  private
    FConnected : Boolean;
    FExtensions: TStringDynArray;
    FHostName: String;
    FIndexName: String;
    FLimit: Cardinal;
    FMinInfixLen: Integer;
    FMySQLVersion: TMCMySQLClientVersion;
    FOnLog: TMCLogEvent;
    FPort: Word;
    FProtocol: TMCTransport;
    FMySQLConn : TSQLConnector;
    FTrans : TSQLTransaction;
    procedure SetHostName(AValue: String);
    procedure SetIndexName(AValue: String);
    procedure SetMySQLVersion(AValue: TMCMySQLClientVersion);
    procedure SetPort(AValue: Word);
    procedure SetProtocol(AValue: TMCTransport);
  Protected
    // Check if we are disconnected. If not, raise an exception
    Procedure CheckDisconnected;
    // Check if we are connected. If not, raise an exception..
    Procedure CheckConnected;
    // Do logging
    Procedure DoLog(aKind : TMCLogKind; Const aMessage : string);
    Procedure DoLog(aKind : TMCLogKind; Const aFmt : String; Const aArgs : Array of const);
    // Get correct port for transport
    Function GetTransportPort(aTransport : TMCTransport) : Word;
    // Transform an exception to a EManticoreSearch exception. Log the exception
    Function TransformError(E: Exception; const aCommand: String): EManticoreSearch;
    // On muysq, check if transaction is active
    function IsTransActionActive : Boolean;
    // On mysql, start a transaction
    procedure StartTransaction; virtual;
    // On mysql, rollback a transaction. NOOP on http.
    procedure RollbackTransaction; virtual;
    // On mysql, commit a transaction NOOP on http.
    procedure CommitTransaction; virtual;
    // Connection/deconnection NOOP on http.
    Procedure DoMysqlConnect; virtual;
    Procedure DoMySQLDisconnect; virtual;
    //
    // Low-level command execution.
    //
    // MySQL-based commands
    Procedure DoMySQLSingleColCommand(const aCmd: String; aList : TStrings);
    function DoResultCommand(const aCmd: String; aOnResult: TMCSearchResultCallBack; aData: Pointer) : Integer;
    procedure ExecuteMySQLCommand(const aCommand: String); virtual;
    // For search
    function DoMySQLResultCommand(const aCmd: String;  aOnResult: TMCSearchResultCallBack; aData: Pointer) : Integer;
    // HTTP-based commands
    function CreateHTTPCmdURL(aCmd: String; IsSelect: Boolean): string;
    function ExecuteHTTPCommand(const aCommand: String; IsSelect: Boolean): String; virtual;
    function ExecuteHTTPCommandResult(const aCmd: String): TJSONArray;
    Procedure DoHTTPSingleColCommand(const aCmd: String; aList : TStrings);
    // For search
    function DoHTTPResultCommand(const aCmd: String;  aOnResult: TMCSearchResultCallBack; aData: Pointer) : Integer;
    // Commands with result
    // Get declaration of the index table, used in CreateIndex.
    function GetIndexSQL: string;
    // Used During indexing:
    // Actual call to do the indexing
    function DoIndexSources(const aTree, aDir, aBaseDir: String;  aOptions: TMCIndexOptions; aOnProgress : TIndexProgressEvent = Nil): Integer; virtual;

  Public
    // escape a string so it can be used in a Match() operation
    class function Escape(aString: String): String;
  Public
    Constructor Create(aOwner : TComponent); override;
    Destructor Destroy; override;
    // Create a copy with the same connection parameters as this instance
    function Clone(aOwner: TComponent): TManticoreSearchSources; virtual;
    // Connect to manticore
    Procedure Connect;
    // Disconnect from manticore
    Procedure Disconnect;
    // Create the index with given name. If left empty, the IndexName property is used.
    Procedure CreateIndex(const aIndexName : string = '');
    // Truncate the index.
    Procedure TruncateIndex;
    // Delete the current index.
    Procedure DeleteIndex;
    // Delete the indicated index.
    Procedure DeleteIndex(const aIndexName : String);
    // List Indexes
    procedure ListIndexes(aList : TStrings);
    Function ListIndexes : TStringDynArray;
    // List trees for IndexName
    procedure ListTrees(aList : TStrings);
    Function ListTrees : TStringDynArray;
    // Delete the source tree in the index.
    Procedure DeleteTree(const aTree : String);
    // Execute an arbitrary ManticoreSearch command
    procedure ExecuteCommand(const aCommand: String; IsSelect: Boolean);
    // See if extension is in list of extensions
    function AllowExtension(aExtension: String): Boolean;
    // Index a source file aFile in source tree aTree.
    procedure IndexSourceFile(const aTree, aStoredFileName, aActualFileName: String);
    // Index files using aTree, starting in directory aDir, using given options
    Function IndexSources(const aTree, aDir: String; aOptions: TMCIndexOptions; aOnProgress : TIndexProgressEvent = nil) : Integer;
    // Search in all source trees
    Function Search(const aMatchTerm : String) : TMCSearchResultArray;
    // Search in source tree
    Function Search(const aMatchTerm : String; Const aTree : String) : TMCSearchResultArray;
    // Search in source trees
    Function Search(const aMatchTerm : String; Const aTrees : Array of String) : TMCSearchResultArray;
    // Call aOnResult with aData for every result. Return number of results
    Function Search(const aMatchTerm : String; Const aTrees : Array of String; aOnResult : TMCSearchResultCallBack; aData : Pointer) : Integer;
    // Create your own command
    function ResultCommand(const aCmd: String; aOnResult: TMCSearchResultCallBack; aData: Pointer) : Integer;
    // Run a command that returns a single column. Values are stored in aList
    Procedure SingleColCommand(const aCmd: String; aList : TStrings);
    // Run a command that returns a single value. If no results are returned then the result is the empty string;
    Function SingleValueCommand(const aCmd: String) : String;
    // Are we currently connected ?
    Property Connected : Boolean Read FConnected;
    // Extensions to use when searching files
    Property Extensions : TStringDynArray Read FExtensions Write FExtensions;
  Published
    // Client library version to use when connecting to manticore
    Property MySQLVersion : TMCMySQLClientVersion Read FMySQLVersion Write SetMySQLVersion;
    // Transport to use.
    Property Transport : TMCTransport Read FProtocol Write SetProtocol;
    // Hostname
    Property HostName : String Read FHostName Write SetHostName;
    // Port may differ, depending on transport. If left empty, the default for the current protocol will be used.
    Property Port : Word Read FPort Write SetPort;
    // IndexName to use
    Property IndexName : String Read FIndexName Write SetIndexName;
    // Limit number of results. If 0, the manticoresearch default is used.
    Property Limit : Cardinal Read FLimit Write FLimit;
    // Minimum infix len when creating index. Must be 2 or higher to enable partial matches
    Property MinInfixLen : Integer Read FMinInfixLen Write FMinInfixLen Default DefaultMCMinInfixLen;
    // Log event
    Property OnLog : TMCLogEvent Read FOnLog Write FOnLog;
  end;
  TManticoreSearchSourcesClass = Class of TManticoreSearchSources;

Const
  MySQLConnNames : Array[TMCMySQLClientVersion] of string = ('','MySQL 5.7','MySQL 8.0');
  MCTransportNames : Array[TMCTransport] of string = ('','MySQL','HTTP');

implementation

uses fphttpclient, httpprotocol;

{ TMCToArrayConverter }

constructor TMCToArrayConverter.Create(aGrowDelta: Cardinal);
begin
  FGrowDelta:=aGrowDelta;
  if FGrowDelta=0 then
    FGrowDelta:=20;
end;

procedure TMCToArrayConverter.DoAddToResult(Sender: TObject;
  const aResult: TMCSearchResult; aData: Pointer; var aContinue: Boolean);

Var
  Len : Integer;

begin
  Len:=Length(Results);
  if Count>=Len then
    SetLength(Results,Len+FGrowDelta);
  Results[Count]:=aResult;
  Inc(Count);
  aContinue:=True;
end;


{ TMCSearchResult }

function TMCSearchResult.Description(aFull: Boolean): string;
begin
  Result:=Format('%s(%d): %s',[FileName,LineNo,Content]);
  if aFull then
    Result:='['+Tree+']'+Result
end;


{ TManticoreSearchSources }

procedure TManticoreSearchSources.SetHostName(AValue: String);
begin
  if FHostName=AValue then Exit;
  CheckDisconnected;
  FHostName:=AValue;
end;

procedure TManticoreSearchSources.SetIndexName(AValue: String);
begin
  if FIndexName=AValue then Exit;
  CheckDisconnected;
  FIndexName:=AValue;
end;

procedure TManticoreSearchSources.SetMySQLVersion(
  AValue: TMCMySQLClientVersion);
begin
  if FMySQLVersion=AValue then Exit;
  CheckDisconnected;
  FMySQLVersion:=AValue;
end;

procedure TManticoreSearchSources.SetPort(AValue: Word);
begin
  if FPort=AValue then Exit;
  CheckDisconnected;
  FPort:=AValue;
end;

procedure TManticoreSearchSources.SetProtocol(AValue: TMCTransport);
begin
  if FProtocol=AValue then Exit;
  CheckDisconnected;
  FProtocol:=AValue;
end;



procedure TManticoreSearchSources.DoLog(aKind: TMCLogKind;
  const aMessage: string);
begin
  if Assigned(FOnLog) then
    FOnLog(Self,aKind,aMessage);
end;

procedure TManticoreSearchSources.DoLog(aKind: TMCLogKind;
  const aFmt: String; const aArgs: array of const);
begin
  DoLog(aKind,Format(aFmt,aArgs));
end;


function TManticoreSearchSources.GetTransportPort(aTransport: TMCTransport
  ): Word;
begin
  if Fport<>0 then
    Result:=FPort
  else
    case aTransport of
      mctHttp : Result:=DefaultMCHTTPPort;
      mctMysql : Result:=DefaultMCMySQLPort;
    end;
end;

procedure TManticoreSearchSources.CheckDisconnected;
begin
  if FConnected then
    Raise EManticoreSearch.Create('Cannot perform this operation when connected');
end;

procedure TManticoreSearchSources.CheckConnected;
begin
  if not FConnected then
    Raise EManticoreSearch.Create('Cannot perform this operation when disconnected');
end;

procedure TManticoreSearchSources.DoMysqlConnect;


Var
  EM : EManticoreSearch;

begin
  If (Transport<>mctMySQL) then
    Raise EManticoreSearch.Create('Internal error: attempting MySQL connection when transport is not mysql');
  If (MySQLVersion=mcvNone) then
    Raise EManticoreSearch.Create('Attempting MySQL connection without MySQLVersion set');

  EM:=Nil;
  FTrans:=Nil;
  FMySQLConn:=TSQLConnector.Create(Self);
  FMySQLConn.HostName:=Self.HostName;
  if FMySQLConn.HostName='' then
    FMySQLConn.HostName:='0';
  FMySQLConn.Params.Values['Port']:=IntToStr(GetTransportPort(mctMysql));
  FMySQLConn.ConnectorType:=MySQLConnNames[MySQLVersion];
  // Keep SQLDB happy, these make no sense for manticore.
  FMySQLConn.DatabaseName:='Dummy';
//  FMySQLConn.UserName:='Dummy';
//  FMySQLConn.Password:='Dummy';
  FTrans:=TSQLTransaction.Create(Self);
  try
    FMySQLConn.Transaction:=FTrans;
    FMySQLConn.Connected:=true;
    FConnected:=true
  except
    on E : Exception do
      begin
      FreeAndNil(FTrans);
      FreeAndNil(FMySQLConn);
      EM:=TransformError(E,'Connect');
      end;
  end;
  if Assigned(EM) then
    Raise EM;
end;

procedure TManticoreSearchSources.DoMySQLDisconnect;
begin
  FConnected:=False;
  FreeAndNil(FTrans);
  FreeAndNil(FMySQLConn);
end;

constructor TManticoreSearchSources.Create(aOwner: TComponent);
begin
  inherited Create(aOwner);
  FMinInfixLen:=DefaultMCMinInfixLen;
  FIndexName:=DefaultMCIndexName;
end;

destructor TManticoreSearchSources.Destroy;
begin
  try
    Disconnect;
  except
    // MySQL connection sometimes burps after long inactivity
  end;
  inherited Destroy;
end;

function TManticoreSearchSources.Clone(aOwner : TComponent): TManticoreSearchSources;
begin
  Result:=TManticoreSearchSourcesClass(Self.ClassType).Create(aOwner);
  Result.Extensions:=Self.Extensions;
  Result.HostName:=Self.HostName;
  Result.IndexName:=Self.IndexName;
  Result.Limit:=Self.Limit;
  Result.MinInfixLen:=Self.MinInfixLen;
  Result.MySQLVersion:=Self.MySQLVersion;
  Result.OnLog:=Self.OnLog;
  Result.Port:=Self.Port;
  Result.Transport:=Self.Transport;
end;

procedure TManticoreSearchSources.Connect;
begin
  if Connected then
    exit;
  If (Transport=mctNone) then
    Raise EManticoreSearch.Create('No transport selected');
  If (Transport=mctHttp) then
    FConnected:=True
  else
    DoMySQLConnect;
end;

procedure TManticoreSearchSources.Disconnect;
begin
  if not Connected then
    exit;
  try
    If (Transport=mctHttp) then
      FConnected:=False
    else
      DoMySQLDisConnect;
  except
    On E : Exception do
      DoLog(mlkError,Format('Error %s while disconnecting: %s',[E.ClassName,E.Message]));
  end;
end;

function TManticoreSearchSources.GetIndexSQL : string;

begin
  if MinInfixLen=1 then
    MinInfixLen:=2;
  Result:=Format('(tree string, filename string, lineno int, line text) min_infix_len = ''%d'' ',[MinInfixLen]);
end;

function TManticoreSearchSources.TransformError(E: Exception;
  const aCommand: String): EManticoreSearch;

begin
  DoLog(mlkError,Format('Error %s with message "%s" executing command "%s"',[E.ClassName,E.Message,aCommand]));
  Result:=EManticoreSearch.Create(E.Message);
  Result.ManticoreCommand:=aCommand;
end;

function TManticoreSearchSources.IsTransActionActive: Boolean;
begin
  if Transport=mctMysql then
    Result:=FTrans.Active
  else
    Result:=True;
end;


procedure TManticoreSearchSources.ExecuteMySQLCommand(
  const aCommand: String);

Var
  SQL : TSQLStatement;
  EM : EManticoreSearch;
  doTrans : Boolean;

begin
  EM:=nil;
  SQL:=TSQLStatement.Create(Self);
  try
    SQL.Database:=FMySQLConn;
    SQL.Transaction:=FTrans;
    doTrans:=Not FTrans.Active;
    if doTrans then
      StartTransaction;
    // Avoid parsing
    SQL.SQL.Clear;
    DoLog(mlkDebug,'Executing command: '+aCommand);
    SQL.SQL.Add(aCommand);
    SQL.Execute;
    if doTrans then
      CommitTransaction;
  except
    On E : exception do
      begin
      if doTrans then
        RollBackTransaction;
      EM:=TransFormError(E,aCommand);
      end;
  end;
  SQL.Free;
  if Assigned(EM) then
    Raise EM;
end;

procedure TManticoreSearchSources.DoMySQLSingleColCommand(const aCmd: String; aList: TStrings);
Var
  Q : TSQLQuery;

begin
  Q:=TSQLQuery.Create(Self);
  try
    Q.DataBase:=FMySQLConn;
    Q.Transaction:=FTrans;
    Q.SQL.Clear;
    Q.SQL.Add(aCmd);
    // Disable fetching indexes !
    Q.UsePrimaryKeyAsKey:=False;
    Q.UniDirectional:=True;
    Q.Open;
    While not Q.EOF do
      begin
      aList.Add(Q.Fields[0].AsString);
      Q.Next;
      end;
  finally
    Q.Free;
  end;
end;

function TManticoreSearchSources.ExecuteHTTPCommandResult(const aCmd: String) : TJSONArray;

var
  lJSON : String;
  aData : TJSONData;

begin
  aData:=Nil;
  lJSON:=ExecuteHTTPCommand(aCmd,True);
  try
    aData:=GetJSON(lJSON);
    if aData is TJSONArray then
      begin
      Result:=TJSONArray(aData);
      aData:=nil;
      end
    else
      Raise EJSON.Create('Command result is not an array: '+lJSON);
  except
    aData.Free;
    Raise;
  end;
end;
procedure TManticoreSearchSources.DoHTTPSingleColCommand(const aCmd: String; aList: TStrings);

Var
  aJSON : TJSONData;
  aSet,aResult : TJSONEnum;
  aResultRecord : TJSONObject;
  aResultPart : TJSONArray;


begin
  aJSON:=ExecuteHTTPCommandResult(aCmd);
  for aSet in aJSON do
    if aSet.Value is TJSONObject then
      begin
      aResultPart:=TJSONObject(aSet.Value).Get('data',TJSONArray(Nil));
      if Assigned(aResultPart) then
        For aResult in aResultPart do
          if aResult.Value is TJSONObject then
            begin
            aResultRecord:=TJSONObject(aResult.Value);
            if (aResultRecord.Count>0) and
                not (aResultRecord.Items[0].JSONType in StructuredJSONTypes) then
              aList.Add(aResultRecord.Items[0].AsString);
            end;
      end;
end;

function TManticoreSearchSources.CreateHTTPCmdURL(aCmd : String; IsSelect : Boolean) : string;


  Function EscapeHTML(aCmd : string) : String;

  begin
    Result:=HTTPEncode(aCmd);
  end;


Const
  // Use SQL query, to return JSON
  BaseSelectURL = 'http://%s:%d/sql?mode=raw&query=%s';
  BaseCliURL = 'http://%s:%d/cli?%s';

Var
  lBase,lCmd,lHostName : String;

begin
  if IsSelect then
    lBase:=BaseSelectURL
  else
    lBase:=BaseCliURL;
  lHostName:=HostName;
  if lHostName='' then
    lHostName:='127.0.0.1';
  lCmd:=EscapeHTML(aCmd);
  Result:=Format(lBase,[lHostName,GetTransportPort(mctHttp),lCmd]);
end;

function TManticoreSearchSources.ExecuteHTTPCommand(const aCommand: String; IsSelect : Boolean) : String;

Var
  HTTP : TFPHTTPClient;
  EM : EManticoreSearch;
  aURL : String;

begin
  EM:=nil;
  HTTP:=TFPHTTPClient.Create(Self);
  try
    aURL:=CreateHTTPCmdURL(aCommand,IsSelect);
    DoLog(mlkDebug,'Getting URL: '+aURL);
    Result:=HTTP.Get(aURL);
  except
    On E : exception do
      EM:=TransFormError(E,aCommand);
  end;
  HTTP.Free;
  if Assigned(EM) then
    Raise EM;
end;

procedure TManticoreSearchSources.ExecuteCommand(const aCommand: String; IsSelect : Boolean);

begin
  DoLog(mlkDebug,'Executing command '+aCommand);
  if FProtocol=mctMysql then
    ExecuteMySQLCommand(aCommand)
  else
    ExecuteHTTPCommand(aCommand, isSelect);
end;


class function TManticoreSearchSources.Escape(aString: String): String;

var
  a : Char;

begin
  Result:=StringReplace(aString,'\','\\',[rfReplaceAll]);
  Result:=StringReplace(Result,'''','\''',[rfReplaceAll]);
  For a in ['(',')','|','-','!','@','~','"','&','^','$','=','<'] do
    Result:=StringReplace(Result,a,'\'+a,[rfReplaceAll]);
end;


procedure TManticoreSearchSources.StartTransaction;

begin
  If Transport=mctMysql then
    FTrans.StartTransaction;
end;

procedure TManticoreSearchSources.CommitTransaction;

begin
  If Transport=mctMysql then
    FTrans.Commit;
end;

procedure TManticoreSearchSources.RollbackTransaction;

begin
  If Transport=mctMysql then
    FTrans.Rollback;
end;

procedure TManticoreSearchSources.IndexSourceFile(const aTree, aStoredFileName, aActualFileName: String);


Const
  SQL = 'INSERT INTO %s (id,tree,filename,lineno,line) values (0,''%s'',''%s'',%d,''%s'');';

Var
  F : Text;
  aLineNo : Integer;
  aLine : String;
  lSQL,lTree,lFile : String;
  doTrans : Boolean;
begin
  CheckConnected;
  doTrans:=Not IsTransActionActive;
  if DoTrans then
    StartTransaction;
  try
    DoLog(mlkInfo,'Indexing file "%s" using stored filename "%s" ',[aActualFileName,aStoredFileName]);
    lTree:=Escape(aTree);
    lFile:=Escape(aStoredFileName);
    AssignFile(F,aActualFileName);
    Reset(F);
    aLineNo:=0;
    While not EOF(F) do
      begin
      Inc(aLineNo);
      ReadLn(F,aLine);
      lSQL:=Format(SQL,[IndexName,lTree,lFile,aLineNo,Escape(aLine)]);
      ExecuteCommand(lsql,False);
      end;
    CloseFile(F);
    if DoTrans then
      CommitTransaction;
  except
    if DoTrans then
      RollBackTransaction;
    Raise;
  end;
end;


function TManticoreSearchSources.AllowExtension(aExtension: String): Boolean;

Var
  S : String;

begin
  if (aExtension<>'') and (aExtension[1]='.') then
    Delete(aExtension,1,1);
  Result:=Length(FExtensions)=0;
  if Not Result then
    for S in FExtensions do
      if SameText(S,aExtension) then
          Exit(True);
end;

function TManticoreSearchSources.DoIndexSources(const aTree, aDir,
  aBaseDir: String; aOptions: TMCIndexOptions; aOnProgress : TIndexProgressEvent): Integer;

Var
  Info : TSearchRec;
  DoContinue,StoreRelative,allFiles : Boolean;
  lActual,lStored : String;

begin
  Result:=0;
  allFiles:=ioAllFiles in aOptions;
  StoreRelative:=ioStoreRelativeNames in aOptions;
  DoContinue:=True;
  If FindFirst(aDir+'*.*',0,Info)=0 then
    try
      Repeat
        if (Info.Attr and faDirectory)=0 then
          if  AllFiles or AllowExtension(ExtractFileExt(Info.Name)) then
            begin
            lActual:=aDir+Info.Name;
            if StoreRelative then
              lStored:=ExtractRelativePath(aBaseDir,lActual)
            else
              lActual:=lStored;
            IndexSourceFile(aTree,lStored,lActual);
            Inc(Result);
            if Assigned(aOnProgress) then
              aOnProgress(Self,lActual,DoContinue);
            end;
      Until (FindNext(Info)<>0) or not DoContinue;
    finally
      FindClose(Info)
    end;
  if (ioRecurse in aOptions) and DoContinue then
    If FindFirst(aDir+AllFilesMask,faDirectory,Info)=0 then
      try
        Repeat
          if ((Info.Attr and faDirectory)=faDirectory) and (Info.Name<>'.') and (Info.Name<>'..') then
            begin
            Result:=Result+DoIndexSources(aTree,aDir+Info.Name+PathDelim,aBaseDir,aOptions,aOnProgress);
            if Assigned(aOnProgress) then
              aOnProgress(Self,lActual,DoContinue);
            end;
        Until (FindNext(Info)<>0) or Not DoContinue;
      finally
        FindClose(Info)
      end;
end;

function TManticoreSearchSources.IndexSources(const aTree, aDir: String;
  aOptions: TMCIndexOptions; aOnProgress : TIndexProgressEvent = nil): Integer;

Var
  lDir : String;

begin
  lDir:=IncludeTrailingPathDelimiter(aDir);
  Result:=DoIndexSources(aTree,lDir,lDir,aOptions,aOnProgress);
end;

function TManticoreSearchSources.Search(const aMatchTerm: String
  ): TMCSearchResultArray;
begin
  Result:=Search(aMatchTerm,[]);
end;

function TManticoreSearchSources.Search(const aMatchTerm: String;
  const aTree: String): TMCSearchResultArray;
begin
  if aTree<>'' then
    Result:=Search(aMatchTerm,[aTree])
  else
    Result:=Search(aMatchTerm,[])
end;

function TManticoreSearchSources.Search(const aMatchTerm: String;
  const aTrees: array of String): TMCSearchResultArray;

Var
  aCollector : TMCToArrayConverter;

begin
  aCollector:=TMCToArrayConverter.Create(Limit);
  try
    Search(aMatchTerm,aTrees,@aCollector.DoAddToResult,Self);
    Result:=aCollector.Results;
    SetLength(Result,aCollector.Count);
  finally
    aCollector.Free;
  end;
end;

function TManticoreSearchSources.DoMySQLResultCommand(const aCmd : String; aOnResult: TMCSearchResultCallBack; aData: Pointer) : Integer;

Var
  Q : TSQLQuery;
  Res : TMCSearchResult;
  FID,FWeight,FLineNo,FFileName,FTree,FContent : TField;
  aContinue : Boolean;

begin
  CheckConnected;
  Result:=0;
  aContinue:=True;
  Q:=TSQLQuery.Create(Self);
  try
    Q.DataBase:=FMySQLConn;
    Q.Transaction:=FTrans;
    Q.SQL.Clear;
    Q.SQL.Add(aCmd);
    // Disable fetching indexes !
    Q.UsePrimaryKeyAsKey:=False;
    Q.UniDirectional:=True;
    Q.Open;
    if Q.IsEmpty then
      exit; // Manticore search does not return field definitions if the result is empty
    FWeight:=Q.FieldByName('theweight');
    FLineNo:=Q.FieldByName('lineno');
    FFileName:=Q.FieldByName('filename');
    FTree:=Q.FieldByName('tree');
    FContent:=Q.FieldByName('line');
    FID:=Q.FieldByName('id');
    While not Q.EOF do
      begin
      Inc(Result);
      Res.FileName:=FFileName.AsString;
      Res.LineNo:=FLineNo.AsInteger;
      Res.Content:=FContent.AsString;
      Res.Weight:=FWeight.Asinteger;
      Res.Tree:=FTree.AsString;
      Res.ID:=FID.AsLargeInt;
      aOnResult(Self,Res,aData,aContinue);
      if not aContinue then
        break;
      Q.Next;

      end;
  finally
    Q.Free;
  end;
end;

function TManticoreSearchSources.DoHTTPResultCommand(const aCmd : String; aOnResult: TMCSearchResultCallBack; aData: Pointer) : Integer;

Var
  aJSON : TJSONArray;
  aSet,aResult : TJSONEnum;
  aResultRecord : TJSONObject;
  aResultPart : TJSONArray;
  Res : TMCSearchResult;
  Continue : Boolean;

begin
  Result:=0;
  Continue:=True;
  aJSON:=ExecuteHTTPCommandResult(aCmd);
  for aSet in aJSON do
    if aSet.Value is TJSONObject then
      begin
      aResultPart:=TJSONObject(aSet.Value).Get('data',TJSONArray(Nil));
      if Assigned(aResultPart) then
        For aResult in aResultPart do
          if aResult.Value is TJSONObject then
            begin
            aResultRecord:=TJSONObject(aResult.Value);
            Res.Weight:=aResultRecord.Get('theweight',Integer(0));
            Res.LineNo:=aResultRecord.Get('lineno',0);
            Res.FileName:=aResultRecord.Get('filename','');
            Res.Tree:=aResultRecord.Get('tree','');
            Res.Content:=aResultRecord.Get('line','');
            Res.ID:=aResultRecord.Get('id',Int64(0));
            inc(Result);
            aOnResult(Self,Res,aData,Continue);
            if not Continue then
              Break;
            end;
      if not Continue then
        Break;
      end;

end;

function TManticoreSearchSources.DoResultCommand(const aCmd: String;
  aOnResult: TMCSearchResultCallBack; aData: Pointer): Integer;

Var
  EM : EManticoreSearch;

begin
  EM:=Nil;
  try
    if Transport=mctMysql then
      Result:=DoMySQLResultCommand(aCmd,aOnResult,aData)
    else
      Result:=DoHTTPResultCommand(aCmd,aOnResult,aData)
  except
    On E : Exception do
      EM:=TransformError(E,aCmd);
  end;
  if Assigned(EM) then
    Raise EM;
end;

function TManticoreSearchSources.Search(const aMatchTerm: String;
  const aTrees: array of String; aOnResult: TMCSearchResultCallBack;
  aData: Pointer): Integer;

Const
  BaseSQL ='select weight() as theweight, * from %s where MATCH(''%s'')';

Var
  aInTrees,aCmd,aTree : String;

begin

  aCmd:=Format(BaseSQL,[IndexName,aMatchTerm]);
  aInTrees:='';
  for aTree in aTrees do
    begin
    if aInTrees<>'' then
      aInTrees:=aInTrees+' OR ';
    aInTrees:=aInTrees+Format('(tree=''%s'')',[Escape(aTree)]);
    end;
  if aInTrees<>'' then
    aCmd:=aCmd+' AND ('+aInTrees+')';
  if FLimit>0 then
    aCmd:=aCmd+Format(' LIMIT %d',[FLimit]);
//  aCmd:='select weight() as theweight, * from sources where MATCH(''*load*'') and (tree<>''base'');';
//  aCmd:='SELECT weight() as theweight, id, tree, line, filename, lineno FROM sources where MATCH(''*load*'') and (tree<>''base'');';
//  aCmd:='SELECT * FROM sources where MATCH(''*load*'')';
  Result:=DoResultCommand(aCmd+';',aOnResult,aData);
end;

function TManticoreSearchSources.ResultCommand(const aCmd: String;
  aOnResult: TMCSearchResultCallBack; aData: Pointer): Integer;
begin
  Result:=DoResultCommand(aCmd,aOnResult,aData);
end;

procedure TManticoreSearchSources.SingleColCommand(const aCmd: String; aList: TStrings);

Var
  EM : EManticoreSearch;

begin
  CheckConnected;
  EM:=nil;
  try
    if Transport=mctMysql then
      DoMySQLSingleColCommand(aCmd,aList)
    else
      DoHTTPSingleColCommand(aCmd,aList)
  except
    On E : Exception do
      EM:=TransformError(E,aCmd);
  end;
  if Assigned(Em) then
    Raise Em;
end;

function TManticoreSearchSources.SingleValueCommand(const aCmd: String): String;

Var
  L : TStringList;

begin
  Result:='';
  L:=TStringList.Create;
  try
    SingleColCommand(aCmd,L);
    if L.Count>1 then
      Raise EManticoreSearch.Create('Multiple results returned for command : '+aCmd);
    if L.Count=1 then
      Result:=L[0];
  finally
    L.Free;
  end;
end;


procedure TManticoreSearchSources.CreateIndex(const aIndexName: string);

Var
  lIndex : String;

begin
  lIndex:=aIndexName;
  if lIndex='' then
    lIndex:=Self.IndexName;
  ExecuteCommand('CREATE TABLE '+lIndex+' '+GetIndexSQL,False);
end;

procedure TManticoreSearchSources.TruncateIndex;
begin
  ExecuteCommand('TRUNCATE TABLE '+IndexName,False);
end;

procedure TManticoreSearchSources.DeleteIndex;
begin
  DeleteIndex(Self.IndexName);
end;

procedure TManticoreSearchSources.DeleteIndex(const aIndexName : string);
begin
  ExecuteCommand('DROP TABLE '+aIndexName,False);
end;


procedure TManticoreSearchSources.ListIndexes(aList: TStrings);
begin
  SingleColCommand('SHOW TABLES',aList);
end;

function TManticoreSearchSources.ListIndexes: TStringDynArray;

Var
  L : TStringList;

begin
  L:=TStringList.Create;
  try
    ListIndexes(L);
    Result:=L.ToStringArray;
  finally
    L.Free;
  end;
end;

procedure TManticoreSearchSources.ListTrees(aList: TStrings);
begin
  SingleColCommand(Format('select tree from %s group by tree',[IndexName]),aList);
end;

function TManticoreSearchSources.ListTrees: TStringDynArray;

Var
  L : TStringList;

begin
  L:=TStringList.Create;
  try
    ListTrees(L);
    Result:=L.ToStringArray;
  finally
    L.Free;
  end;
end;

procedure TManticoreSearchSources.DeleteTree(const aTree: String);
begin
  ExecuteCommand('DELETE FROM '+IndexName+' where (tree='''+Escape(aTree)+''');',False);
end;

end.