mORMot and Open Source friends
Check-in [9b60596cae]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:{902} ExeVerionRetrieve() replaced by the more explicit SetExecutableVersion() function - this commit also includes several fixes for the Linux platform
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 9b60596cae90cb55f269261b4e1431ac6c55d9f6
User & Date: ab 2015-02-15 13:15:41
Context
2015-02-15
13:20
{903} fixed ARM Linux compilation check-in: 93c780fe9b user: ab tags: trunk
13:15
{902} ExeVerionRetrieve() replaced by the more explicit SetExecutableVersion() function - this commit also includes several fixes for the Linux platform check-in: 9b60596cae user: ab tags: trunk
06:59
{901} added TDocVariantData.SortByName method check-in: b38f4de17d user: ab tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to SQLite3/Documentation/Synopse SQLite3 Framework.pro.

1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
....
1635
1636
1637
1638
1639
1640
1641

1642
1643
1644
1645
1646
1647
1648
You may also trans-type your {\f1\fs20 variant} instance into a {\f1\fs20 TDocVariantData record}, and access directly to its internals.\line For instance:
! TDocVariantData(V1).AddValue('comment','Nice guy');
! with TDocVariantData(V1) do             // direct transtyping
!   if Kind=dvObject then                 // direct access to the TDocVariantKind field
!   for i := 0 to Count-1 do              // direct access to the Count: integer field
!     writeln(Names[i],'=',Values[i]);    // direct access to the internal storage arrays
By definition, trans-typing via a {\f1\fs20 TDocVariantData record} is slightly faster than using late-binding.
But you must ensure that the {\f1\fs20 variant} instance is really a {\f1\fs20 TDocVariant} kind of data before transtyping e.g. by calling {\f1\fs20 DocVariantType.IsOfType(aVariant)} or the {\f1\fs20 DocVariantData(aVariant)^} function, which works even for members returned as {\f1\fs20 varByRef} via late binding:
! if DocVariantType.IsOfType(V1) then
! with TDocVariantData(V1) do             // direct transtyping
!   for i := 0 to Count-1 do              // direct access to the Count: integer field
!     writeln(Names[i],'=',Values[i]);    // direct access to the internal storage arrays
!
! writeln(V2.doc); // will write  '{"name":"john","doc":{"one":1,"two":2.5}}'
! if DocVariantType.IsOfType(V2.Doc) then // will be false, since V2.Doc is a varByRef variant
................................................................................
!   writeln('never run');                 // .. so TDocVariantData(V2.doc) will fail
! with DocVariantData(V2.Doc)^ do         // note ^ to de-reference into TDocVariantData
!   for i := 0 to Count-1 do              // direct access the TDocVariantData methods
!     writeln(Names[i],'=',Values[i]);
!  // will write to the console:
!  //  one=1
!  //  two=2.5

You can also allocate directly the {\f1\fs20 TDocVariantData} instance on stack, if you do not need any {\f1\fs20 variant}-oriented access to the object, but just some local storage:
!var Doc1,Doc2: TDocVariantData;
! ...
!  Doc1.Init; // needed for proper initialization
!  assert(Doc1.Kind=dvUndefined);
!  Doc1.AddValue('name','John');        // add some properties
!  Doc1.AddValue('birthyear',1972);






|







 







>







1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
....
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
You may also trans-type your {\f1\fs20 variant} instance into a {\f1\fs20 TDocVariantData record}, and access directly to its internals.\line For instance:
! TDocVariantData(V1).AddValue('comment','Nice guy');
! with TDocVariantData(V1) do             // direct transtyping
!   if Kind=dvObject then                 // direct access to the TDocVariantKind field
!   for i := 0 to Count-1 do              // direct access to the Count: integer field
!     writeln(Names[i],'=',Values[i]);    // direct access to the internal storage arrays
By definition, trans-typing via a {\f1\fs20 TDocVariantData record} is slightly faster than using late-binding.
But you must ensure that the {\f1\fs20 variant} instance is really a {\f1\fs20 TDocVariant} kind of data before transtyping e.g. by calling {\f1\fs20 DocVariantType.IsOfType(aVariant)} or the {\f1\fs20 DocVariantData(aVariant)^} or {\f1\fs20 DocVariantDataSafe(aVariant)^} functions, which both will work even for members returned as {\f1\fs20 varByRef} via late binding (e.g. {\f1\fs20 V2.doc}):
! if DocVariantType.IsOfType(V1) then
! with TDocVariantData(V1) do             // direct transtyping
!   for i := 0 to Count-1 do              // direct access to the Count: integer field
!     writeln(Names[i],'=',Values[i]);    // direct access to the internal storage arrays
!
! writeln(V2.doc); // will write  '{"name":"john","doc":{"one":1,"two":2.5}}'
! if DocVariantType.IsOfType(V2.Doc) then // will be false, since V2.Doc is a varByRef variant
................................................................................
!   writeln('never run');                 // .. so TDocVariantData(V2.doc) will fail
! with DocVariantData(V2.Doc)^ do         // note ^ to de-reference into TDocVariantData
!   for i := 0 to Count-1 do              // direct access the TDocVariantData methods
!     writeln(Names[i],'=',Values[i]);
!  // will write to the console:
!  //  one=1
!  //  two=2.5
In practice, {\f1\fs20 DocVariantDataSafe(aVariant)^} may be preferred, since {\f1\fs20 DocVariantData(aVariant)^} would raise an {\f1\fs20 EDocVariant} exception if {\f1\fs20 aVariant} is not a {\f1\fs20 TDocVariant}, but {\f1\fs20 DocVariantDataSafe(aVariant)^} would return a "fake" void {\f1\fs20 DocVariant} instance, in which {\f1\fs20 Count=0} and {\f1\fs20 Kind=dbUndefined}.
You can also allocate directly the {\f1\fs20 TDocVariantData} instance on stack, if you do not need any {\f1\fs20 variant}-oriented access to the object, but just some local storage:
!var Doc1,Doc2: TDocVariantData;
! ...
!  Doc1.Init; // needed for proper initialization
!  assert(Doc1.Kind=dvUndefined);
!  Doc1.AddValue('name','John');        // add some properties
!  Doc1.AddValue('birthyear',1972);

Changes to SQLite3/Samples/01 - In Memory ORM/Project01.dpr.

29
30
31
32
33
34
35

36
37
38
39
40
41
42
43
44
45
46
47
48
49
}

program Project01;

uses
  Forms,
  SysUtils,

  mORMot,
  Unit1 in 'Unit1.pas' {Form1},
  SampleData in 'SampleData.pas';

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Form1.Caption := ' Sample 01 - In Memory ORM';
  Form1.Database := TSQLRestStorageInMemory.Create(TSQLSampleRecord,nil,
    ChangeFileExt(paramstr(0),'.db'));
  Application.Run;
end.






>











|


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
}

program Project01;

uses
  Forms,
  SysUtils,
  SynCommons,
  mORMot,
  Unit1 in 'Unit1.pas' {Form1},
  SampleData in 'SampleData.pas';

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Form1.Caption := ' Sample 01 - In Memory ORM';
  Form1.Database := TSQLRestStorageInMemory.Create(TSQLSampleRecord,nil,
    ChangeFileExt(ExeVersion.ProgramFileName,'.db'));
  Application.Run;
end.

Changes to SQLite3/Samples/02 - Embedded SQLite3 ORM/Project02.dpr.

30
31
32
33
34
35
36

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
}
program Project02;

uses
  Forms,
  SysUtils,

  mORMot,
  mORMotSQLite3, SynSQLite3Static,
  Unit1 in '..\01 - In Memory ORM\Unit1.pas' {Form1},
  SampleData in '..\01 - In Memory ORM\SampleData.pas';

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Form1.Caption := ' Sample 02 - Embedded SQLite3 ORM';
  Form1.Database := TSQLRestServerDB.Create(Form1.Model,
    ChangeFileExt(paramstr(0),'.db3'));
  TSQLRestServerDB(Form1.Database).CreateMissingTables;
  Application.Run;
end.






>












|



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
}
program Project02;

uses
  Forms,
  SysUtils,
  SynCommons,
  mORMot,
  mORMotSQLite3, SynSQLite3Static,
  Unit1 in '..\01 - In Memory ORM\Unit1.pas' {Form1},
  SampleData in '..\01 - In Memory ORM\SampleData.pas';

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Form1.Caption := ' Sample 02 - Embedded SQLite3 ORM';
  Form1.Database := TSQLRestServerDB.Create(Form1.Model,
    ChangeFileExt(ExeVersion.ProgramFileName,'.db3'));
  TSQLRestServerDB(Form1.Database).CreateMissingTables;
  Application.Run;
end.

Changes to SQLite3/Samples/03 - NamedPipe Client-Server/Unit2.pas.

1
2
3
4
5
6

7
8
9
10
11
12
13
14
..
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, mORMot, mORMotSQLite3, SynSQLite3Static, StdCtrls, SampleData;

type
  TForm1 = class(TForm)
    Label1: TLabel;
    Button1: TButton;
    Label2: TLabel;
    procedure Button1Click(Sender: TObject);
................................................................................
begin
  Close;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Model := CreateSampleModel;
  Server := TSQLRestServerDB.Create(Model,ChangeFileExt(paramstr(0),'.db3'));
  Server.CreateMissingTables;
  Server.ExportServerNamedPipe('03');
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Server.Free;





>
|







 







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs,
  SynCommons, mORMot, mORMotSQLite3, SynSQLite3Static, StdCtrls, SampleData;

type
  TForm1 = class(TForm)
    Label1: TLabel;
    Button1: TButton;
    Label2: TLabel;
    procedure Button1Click(Sender: TObject);
................................................................................
begin
  Close;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Model := CreateSampleModel;
  Server := TSQLRestServerDB.Create(Model,ChangeFileExt(ExeVersion.ProgramFileName,'.db3'));
  Server.CreateMissingTables;
  Server.ExportServerNamedPipe('03');
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Server.Free;

Changes to SQLite3/Samples/04 - HTTP Client-Server/Unit2.pas.

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
begin
  Close;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Model := CreateSampleModel;
  DB := TSQLRestServerDB.Create(Model,ChangeFileExt(paramstr(0),'.db3'),true);
  DB.CreateMissingTables;
  Server := TSQLHttpServer.Create('8080',[DB],'+',HTTP_DEFAULT_MODE);
  Server.AccessControlAllowOrigin := '*'; // allow cross-site AJAX queries
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin






|







38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
begin
  Close;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Model := CreateSampleModel;
  DB := TSQLRestServerDB.Create(Model,ChangeFileExt(ExeVersion.ProgramFileName,'.db3'),true);
  DB.CreateMissingTables;
  Server := TSQLHttpServer.Create('8080',[DB],'+',HTTP_DEFAULT_MODE);
  Server.AccessControlAllowOrigin := '*'; // allow cross-site AJAX queries
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin

Changes to SQLite3/Samples/04 - HTTP Client-Server/Unit2Static.pas.

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
..
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
begin
  Close;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Model := CreateSampleModel;
  DB := TSQLRestServerDB.Create(Model,ChangeFileExt(paramstr(0),'.db3'),true);
  DB.CreateMissingTables;
  Server := TCustomHttpServer.Create('8080',[DB],'+',useHttpApiRegisteringURI,32,secNone,'static');
  Server.AccessControlAllowOrigin := '*'; // allow cross-site AJAX queries
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
................................................................................

function TCustomHttpServer.Request(Ctxt: THttpServerRequest): cardinal;
var FileName: TFileName;
begin
  if (Ctxt.Method='GET') and IdemPChar(pointer(Ctxt.URL),'/STATIC/') and
     (PosEx('..',Ctxt.URL)=0) then begin
    // http.sys will send the specified file from kernel mode
    FileName := ExtractFilePath(ParamStr(0))+'www\'+UTF8ToString(Copy(Ctxt.URL,8,maxInt));
    Ctxt.OutContent := StringToUTF8(FileName);
    Ctxt.OutContentType := HTTP_RESP_STATICFILE;
    result := 200; // THttpApiServer.Execute will return 404 if not found
  end else
    // call the associated TSQLRestServer instance(s)
    result := inherited Request(Ctxt);
end;


end.






|







 







|










45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
..
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
begin
  Close;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Model := CreateSampleModel;
  DB := TSQLRestServerDB.Create(Model,ChangeFileExt(ExeVersion.ProgramFileName,'.db3'),true);
  DB.CreateMissingTables;
  Server := TCustomHttpServer.Create('8080',[DB],'+',useHttpApiRegisteringURI,32,secNone,'static');
  Server.AccessControlAllowOrigin := '*'; // allow cross-site AJAX queries
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
................................................................................

function TCustomHttpServer.Request(Ctxt: THttpServerRequest): cardinal;
var FileName: TFileName;
begin
  if (Ctxt.Method='GET') and IdemPChar(pointer(Ctxt.URL),'/STATIC/') and
     (PosEx('..',Ctxt.URL)=0) then begin
    // http.sys will send the specified file from kernel mode
    FileName := ExeVersion.ProgramFilePath+'www\'+UTF8ToString(Copy(Ctxt.URL,8,maxInt));
    Ctxt.OutContent := StringToUTF8(FileName);
    Ctxt.OutContentType := HTTP_RESP_STATICFILE;
    result := 200; // THttpApiServer.Execute will return 404 if not found
  end else
    // call the associated TSQLRestServer instance(s)
    result := inherited Request(Ctxt);
end;


end.

Changes to SQLite3/Samples/05 - Report created from code/SynPdfFormCanvas.dpr.

2
3
4
5
6
7
8

9
10
11
12
13
14
15
..
50
51
52
53
54
55
56
57
58
59
60
{$APPTYPE CONSOLE}

uses
  SysUtils,
  Math,
  DateUtils,

  SynPDF;

const
  PDFFactor: Single = 72.0 / 2.54;

var
  obPDF: TPdfDocument;
................................................................................
  obPDF.Canvas.TextOut(2.0*PDFFactor,27.0*PDFFactor,'XObject form canvas sample');

  obPDF.Canvas.DrawXObject(2.0*PDFFactor,5.0*PDFFactor,1.0,1.0,'FORMOBJECT');
  obPDF.Canvas.DrawXObject(10.0*PDFFactor,10.0*PDFFactor,1.0,0.5,'FORMOBJECT');
  obPDF.Canvas.DrawXObject(8.0*PDFFactor,15.0*PDFFactor,2.0,2.0,'FORMOBJECT');
  obPDF.Canvas.DrawXObject(2.0*PDFFactor,20.0*PDFFactor,0.5,1.0,'FORMOBJECT');

  obPDF.SaveToFile(ChangeFileExt(ParamStr(0),'.pdf'));

  FreeAndNil(obPDF);
end.






>







 







|



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..
51
52
53
54
55
56
57
58
59
60
61
{$APPTYPE CONSOLE}

uses
  SysUtils,
  Math,
  DateUtils,
  SynCommons,
  SynPDF;

const
  PDFFactor: Single = 72.0 / 2.54;

var
  obPDF: TPdfDocument;
................................................................................
  obPDF.Canvas.TextOut(2.0*PDFFactor,27.0*PDFFactor,'XObject form canvas sample');

  obPDF.Canvas.DrawXObject(2.0*PDFFactor,5.0*PDFFactor,1.0,1.0,'FORMOBJECT');
  obPDF.Canvas.DrawXObject(10.0*PDFFactor,10.0*PDFFactor,1.0,0.5,'FORMOBJECT');
  obPDF.Canvas.DrawXObject(8.0*PDFFactor,15.0*PDFFactor,2.0,2.0,'FORMOBJECT');
  obPDF.Canvas.DrawXObject(2.0*PDFFactor,20.0*PDFFactor,0.5,1.0,'FORMOBJECT');

  obPDF.SaveToFile(ChangeFileExt(ExeVersion.ProgramFileName,'.pdf'));

  FreeAndNil(obPDF);
end.

Changes to SQLite3/Samples/05 - Report created from code/SynPdfLayers.dpr.

2
3
4
5
6
7
8

9
10
11
12
13
14
15
...
121
122
123
124
125
126
127
128
129
130
131
{$APPTYPE CONSOLE}

uses
  SysUtils,
  Math,
  DateUtils,

  SynPDF;

const
  PDFFactor: Single = 72.0 / 2.54;

var
  obPDF: TPdfDocument;
................................................................................

  obPDF.Canvas.TextOut(2.0*PDFFactor,2.0*PDFFactor,'Main Layer 3:');

  obPDF.Canvas.BeginMarkedContent(obMainLayer3);
  obPDF.Canvas.TextOut(10.0*PDFFactor,2.0*PDFFactor,'Text visible in Main Layer 3');
  obPDF.Canvas.EndMarkedContent;

  obPDF.SaveToFile(ChangeFileExt(ParamStr(0),'.pdf'));

  FreeAndNil(obPDF);
end.






>







 







|



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
122
123
124
125
126
127
128
129
130
131
132
{$APPTYPE CONSOLE}

uses
  SysUtils,
  Math,
  DateUtils,
  SynCommons,
  SynPDF;

const
  PDFFactor: Single = 72.0 / 2.54;

var
  obPDF: TPdfDocument;
................................................................................

  obPDF.Canvas.TextOut(2.0*PDFFactor,2.0*PDFFactor,'Main Layer 3:');

  obPDF.Canvas.BeginMarkedContent(obMainLayer3);
  obPDF.Canvas.TextOut(10.0*PDFFactor,2.0*PDFFactor,'Text visible in Main Layer 3');
  obPDF.Canvas.EndMarkedContent;

  obPDF.SaveToFile(ChangeFileExt(ExeVersion.ProgramFileName,'.pdf'));

  FreeAndNil(obPDF);
end.

Changes to SQLite3/Samples/05 - Report created from code/Unit1.pas.

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
...
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
      Font.Style := [fsItalic,fsUnderline];
      TextAlign := taRight;
      AddTextToHeaderAt('http://synopse.info',RightMarginPos);
      Font.Style := [];
      AddLineToFooter(false);
      AddPagesToFooterAt(sPageN,RightMarginPos);
      RestoreSavedLayout;
      AddTextToHeader(ExtractFileName(paramstr(0)));
      AddTextToFooter(DateTimeToStr(Now));
      AddLineToHeader(false);
      Font.Size := 12;
      ExportPDFForceJPEGCompression := 0;

{      // test
      WordWrapLeftCols := true;
................................................................................
    begin
      SetFont('Arial',12,[fsBold]);
      TextOut(100,500,'Test');
      MoveTo(100,400);
      LineTo(500,500);
      Stroke;
    end; }
    FN := ChangeFileExt(paramstr(0),'.pdf');
    SaveToFile(FN);
    ShellExecute(Handle,nil,pointer(FN),nil,nil,SW_SHOWNORMAL);
  finally
    Free;
  end;
  Close;
end;






|







 







|







84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
...
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
      Font.Style := [fsItalic,fsUnderline];
      TextAlign := taRight;
      AddTextToHeaderAt('http://synopse.info',RightMarginPos);
      Font.Style := [];
      AddLineToFooter(false);
      AddPagesToFooterAt(sPageN,RightMarginPos);
      RestoreSavedLayout;
      AddTextToHeader(ExeVersion.ProgramName);
      AddTextToFooter(DateTimeToStr(Now));
      AddLineToHeader(false);
      Font.Size := 12;
      ExportPDFForceJPEGCompression := 0;

{      // test
      WordWrapLeftCols := true;
................................................................................
    begin
      SetFont('Arial',12,[fsBold]);
      TextOut(100,500,'Test');
      MoveTo(100,400);
      LineTo(500,500);
      Stroke;
    end; }
    FN := ChangeFileExt(ExeVersion.ProgramFileName,'.pdf');
    SaveToFile(FN);
    ShellExecute(Handle,nil,pointer(FN),nil,nil,SW_SHOWNORMAL);
  finally
    Free;
  end;
  Close;
end;

Changes to SQLite3/Samples/10 - Background Http service/httpservice.dpr.

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
procedure TSQLite3HttpService.DoStart(Sender: TService);
begin
  TSQLLog.Enter(self);
  if Server<>nil then
    DoStop(nil); // should never happen
  Model := CreateSampleModel;
  DB := TSQLRestServerDB.Create(Model,ChangeFileExt(paramstr(0),'.db3'));
  DB.CreateMissingTables;
  Server := TSQLHttpServer.Create('8080',[DB],'+',useHttpApiRegisteringURI);
  TSQLLog.Add.Log(sllInfo,'Server % started by %',[Server.HttpServer,Server]);
end;

procedure TSQLite3HttpService.DoStop(Sender: TService);
begin






|







87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
procedure TSQLite3HttpService.DoStart(Sender: TService);
begin
  TSQLLog.Enter(self);
  if Server<>nil then
    DoStop(nil); // should never happen
  Model := CreateSampleModel;
  DB := TSQLRestServerDB.Create(Model,ChangeFileExt(ExeVersion.ProgramFileName,'.db3'));
  DB.CreateMissingTables;
  Server := TSQLHttpServer.Create('8080',[DB],'+',useHttpApiRegisteringURI);
  TSQLLog.Add.Log(sllInfo,'Server % started by %',[Server.HttpServer,Server]);
end;

procedure TSQLite3HttpService.DoStop(Sender: TService);
begin

Changes to SQLite3/Samples/10 - Background Http service/httpserviceSetup.dpr.

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  HTTPSERVICENAME = 'mORMotHttpServerService';
  HTTPSERVICEDISPLAYNAME = 'mORMot Http Server Service';

begin
  TSQLLog.Family.Level := LOG_VERBOSE;
  with TServiceController.CreateOpenService('','',HTTPSERVICENAME) do
  try
    CheckParameters(ExtractFilePath(paramstr(0))+'HttpService.exe',
      HTTPSERVICEDISPLAYNAME);
  finally
    Free;
  end;
  TSQLLog.Add.Log(sllTrace,'Quitting command line');
  with TServiceController.CreateOpenService('','',HTTPSERVICENAME) do
  try
    State; // just to log the service state after handling the /parameters
  finally
    Free;
  end;
end.






|












20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  HTTPSERVICENAME = 'mORMotHttpServerService';
  HTTPSERVICEDISPLAYNAME = 'mORMot Http Server Service';

begin
  TSQLLog.Family.Level := LOG_VERBOSE;
  with TServiceController.CreateOpenService('','',HTTPSERVICENAME) do
  try
    CheckParameters(ExeVersion.ProgramFilePath+'HttpService.exe',
      HTTPSERVICEDISPLAYNAME);
  finally
    Free;
  end;
  TSQLLog.Add.Log(sllTrace,'Quitting command line');
  with TServiceController.CreateOpenService('','',HTTPSERVICENAME) do
  try
    State; // just to log the service state after handling the /parameters
  finally
    Free;
  end;
end.

Changes to SQLite3/Samples/11 - Exception logging/LogViewMain.pas.

1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
procedure TMainLogView.btnListSaveClick(Sender: TObject);
begin
  dlgSaveList.FileName := 'Remote '+Utf8ToString(DateTimeToIso8601(Now,false,' '));
  if not dlgSaveList.Execute then
    exit;
  fLog.SaveToFile('temp~.log',
    StringToUTF8(paramstr(0))+' 0.0.0.0 ('+NowToString+')'#13+
    'Host=Remote User=Unknown CPU=Unknown OS=0.0=0.0.0 Wow64=0 Freq=1'#13+
    'LogView '+SYNOPSE_FRAMEWORK_VERSION+' Remote '+NowToString+#13#13);
  if dlgSaveList.FilterIndex=3 then
    FileSynLZ('temp~.log',dlgSaveList.FileName,LOG_MAGIC) else
    RenameFile('temp~.log',dlgSaveList.FileName);
end;

end.






|








1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
procedure TMainLogView.btnListSaveClick(Sender: TObject);
begin
  dlgSaveList.FileName := 'Remote '+Utf8ToString(DateTimeToIso8601(Now,false,' '));
  if not dlgSaveList.Execute then
    exit;
  fLog.SaveToFile('temp~.log',
    StringToUTF8(ExeVersion.ProgramFileName)+' 0.0.0.0 ('+NowToString+')'#13+
    'Host=Remote User=Unknown CPU=Unknown OS=0.0=0.0.0 Wow64=0 Freq=1'#13+
    'LogView '+SYNOPSE_FRAMEWORK_VERSION+' Remote '+NowToString+#13#13);
  if dlgSaveList.FilterIndex=3 then
    FileSynLZ('temp~.log',dlgSaveList.FileName,LOG_MAGIC) else
    RenameFile('temp~.log',dlgSaveList.FileName);
end;

end.

Changes to SQLite3/Samples/12 - SynDB Explorer/SynDBExplorerFrame.pas.

433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
...
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
  end;
end;

constructor TDBExplorerFrame.Create(aOwner: TComponent);
begin
  inherited Create(aOwner);
  fHint := THintWindowDelayed.Create(self);
  fSQLLogFile := ChangeFileExt(paramstr(0),'.history');
  PagesLeft.ActivePageIndex := 0;
end;

destructor TDBExplorerFrame.Destroy;
begin
  FreeAndNil(fGrid);
  inherited;
................................................................................
            Rep.DrawText(GetTableDescription(TableName));
            Rep.NewLine;
          end;
          Rep.WordWrapLeftCols := true;
          TSQLRibbon(nil).AddToReport(Rep,fGrid.Table,[]);
          Rep.EndDoc;
          Rep.Caption := GetFileNameWithoutExt(ExtractFileName(FileName));
          ExeVersionRetrieve;
          Rep.ExportPDFAuthor := U2S(ExeVersion.User);
          Rep.ExportPDFApplication := Form.Caption;
          Rep.ExportPDFSubject := BtnResultToFile.Hint;
          Rep.ExportPDFKeywords := MemoSQL.Text;
          Rep.ExportPDF(FileName,True,false)
        finally
          Rep.Free;






|







 







<







433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
...
500
501
502
503
504
505
506

507
508
509
510
511
512
513
  end;
end;

constructor TDBExplorerFrame.Create(aOwner: TComponent);
begin
  inherited Create(aOwner);
  fHint := THintWindowDelayed.Create(self);
  fSQLLogFile := ChangeFileExt(ExeVersion.ProgramFileName,'.history');
  PagesLeft.ActivePageIndex := 0;
end;

destructor TDBExplorerFrame.Destroy;
begin
  FreeAndNil(fGrid);
  inherited;
................................................................................
            Rep.DrawText(GetTableDescription(TableName));
            Rep.NewLine;
          end;
          Rep.WordWrapLeftCols := true;
          TSQLRibbon(nil).AddToReport(Rep,fGrid.Table,[]);
          Rep.EndDoc;
          Rep.Caption := GetFileNameWithoutExt(ExtractFileName(FileName));

          Rep.ExportPDFAuthor := U2S(ExeVersion.User);
          Rep.ExportPDFApplication := Form.Caption;
          Rep.ExportPDFSubject := BtnResultToFile.Hint;
          Rep.ExportPDFKeywords := MemoSQL.Text;
          Rep.ExportPDF(FileName,True,false)
        finally
          Rep.Free;

Changes to SQLite3/Samples/12 - SynDB Explorer/SynDBExplorerMain.pas.

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
      C.Server := C.Ident;
      TryConnect(C,True);
    finally
      C.Free;
    end;
  end else begin
    Conns := TSQLRestStorageInMemory.Create(
      TSQLConnection,nil,ChangeFileExt(paramstr(0),'.config'),false);
    try
      Conns.ExpandedJSON := true; // for better human reading and modification
      Task.Title := MainCaption;
      Task.Inst := sSelectAConnection;
      Task.Content := sSelectOrCreateAConnection;
      if Conns.Count=0 then
        Btns := [cbCancel] else begin






|







201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
      C.Server := C.Ident;
      TryConnect(C,True);
    finally
      C.Free;
    end;
  end else begin
    Conns := TSQLRestStorageInMemory.Create(
      TSQLConnection,nil,ChangeFileExt(ExeVersion.ProgramFileName,'.config'),false);
    try
      Conns.ExpandedJSON := true; // for better human reading and modification
      Task.Title := MainCaption;
      Task.Inst := sSelectAConnection;
      Task.Content := sSelectOrCreateAConnection;
      if Conns.Count=0 then
        Btns := [cbCancel] else begin

Changes to SQLite3/Samples/14 - Interface based services/Project14Server.dpr.

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
begin
  with TSQLLog.Family do begin
    Level := LOG_VERBOSE;
    EchoToConsole := LOG_VERBOSE; // log all events to the console
  end;
  aModel := TSQLModel.Create([],ROOT_NAME);
  try
    with TSQLRestServerDB.Create(aModel,ChangeFileExt(paramstr(0),'.db'),true) do
    try
      CreateMissingTables; // we need AuthGroup and AuthUser tables
      ServiceDefine(TServiceCalculator,[ICalculator],sicShared);
      if ExportServerNamedPipe(APPLICATION_NAME) then
        writeln('Background server is running.'#10) else
        writeln('Error launching the server'#10);
      write('Press [Enter] to close the server.');






|







24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
begin
  with TSQLLog.Family do begin
    Level := LOG_VERBOSE;
    EchoToConsole := LOG_VERBOSE; // log all events to the console
  end;
  aModel := TSQLModel.Create([],ROOT_NAME);
  try
    with TSQLRestServerDB.Create(aModel,ChangeFileExt(ExeVersion.ProgramFileName,'.db'),true) do
    try
      CreateMissingTables; // we need AuthGroup and AuthUser tables
      ServiceDefine(TServiceCalculator,[ICalculator],sicShared);
      if ExportServerNamedPipe(APPLICATION_NAME) then
        writeln('Background server is running.'#10) else
        writeln('Error launching the server'#10);
      write('Press [Enter] to close the server.');

Changes to SQLite3/Samples/14 - Interface based services/Project14ServerExternal.dpr.

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
end;

var
  aModel: TSQLModel;
  aProps: TSQLDBSQLite3ConnectionProperties;
begin
  aProps := TSQLDBSQLite3ConnectionProperties.Create(
    StringToUtf8(ChangeFileExt(paramstr(0),'.db')),'','','');
  try
    aModel := TSQLModel.Create([TSQLAuthGroup,TSQLAuthUser],ROOT_NAME);
    VirtualTableExternalRegisterAll(aModel,aProps);
    try
      with TSQLRestServerDB.Create(aModel,SQLITE_MEMORY_DATABASE_NAME,true) do
      try
        CreateMissingTables; // we need AuthGroup and AuthUser tables






|







29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
end;

var
  aModel: TSQLModel;
  aProps: TSQLDBSQLite3ConnectionProperties;
begin
  aProps := TSQLDBSQLite3ConnectionProperties.Create(
    StringToUtf8(ChangeFileExt(ExeVersion.ProgramFileName,'.db')),'','','');
  try
    aModel := TSQLModel.Create([TSQLAuthGroup,TSQLAuthUser],ROOT_NAME);
    VirtualTableExternalRegisterAll(aModel,aProps);
    try
      with TSQLRestServerDB.Create(aModel,SQLITE_MEMORY_DATABASE_NAME,true) do
      try
        CreateMissingTables; // we need AuthGroup and AuthUser tables

Changes to SQLite3/Samples/15 - External DB performance/PerfMain.pas.

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
...
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
...
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
...
921
922
923
924
925
926
927
928
929
930
931
    property ReadAllDirectTime: RawUTF8 read fReadAllDirectTime;
    property ReadAllDirectRate: integer read fReadAllDirectRate;
    property ClientCloseTime: RawUTF8 read fClientCloseTime;
  end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  Ini := StringFromFile(ChangeFileExt(paramstr(0),'.ini'));
  OraTNSName.Text := UTF8ToString(FindIniEntry(Ini,'Oracle','TNSName'));
  OraUser.Text := UTF8ToString(FindIniEntry(Ini,'Oracle','User'));
  OraPass.Text := UTF8ToString(FindIniEntry(Ini,'Oracle','Password'));
  Stats := TObjectList.Create;
end;

const
................................................................................
  FIREBIRD_LIB = 'Firebird'+{$ifdef CPU64}'64'+{$endif=}'\fbembed.dll';

procedure TMainForm.BtnRunTestsClick(Sender: TObject);
var T,U,P: RawUTF8;
    props: TSQLDBSQLite3ConnectionProperties;
    server: TSQLDBServerAbstract;
begin
  ExeVersionRetrieve;
  //SynDBLog.Family.Level := LOG_VERBOSE;  // for debugging
  T := StringToUTF8(OraTNSName.Text);
  U := StringToUTF8(OraUser.Text);
  P := StringToUTF8(OraPass.Text);
  UpdateIniEntry(Ini,'Oracle','TNSName',T);
  UpdateIniEntry(Ini,'Oracle','User',U);
  UpdateIniEntry(Ini,'Oracle','Password',P);
  FileFromString(Ini,ChangeFileExt(paramstr(0),'.ini'));
  LogMemo.Clear;
{  FreeAndNil(sqlite3); sqlite3 := TSQLite3LibraryDynamic.Create('sqlite3.dll'); }
  // if false then
  try
  try
    // -------- SQlite3
    //(*
................................................................................
  except
    on E: Exception do
      LogMemo.Lines.Add(E.Message);
  end;
  finally
    Label3.Caption := '';
    T := ObjectToJSON(Stats,[woHumanReadable]);
    FileFromString(T,ChangeFileExt(paramstr(0),'.stats'));
    FileFromString(T,Ansi7ToString(NowToString(false))+'.log');
    SaveStats;
  end;
end;

type
  TSQLRecordSample = class(TSQLRecord)
................................................................................
  for i := 0 to Stats.Count-1 do
    txt := txt+Int32ToUtf8(Stat[i].ReadAllVirtualRate)+',';
  txt[length(txt)] := '|';
  for i := 0 to Stats.Count-1 do
    txt := txt+Int32ToUtf8(Stat[i].ReadAllDirectRate)+',';
  PicEnd(Cat1);

  FileFromString(Doc,ChangeFileExt(paramstr(0),'.txt'));
  FileFromString('<html><body>'#13#10+s,ChangeFileExt(paramstr(0),'.htm'));
end;

procedure TMainForm.FormShow(Sender: TObject);
var Valid: boolean;
    S: RawUTF8;
begin
  btnReport.Visible := DebugHook=0;
................................................................................
    SaveStats;
  Close;
end;


procedure TMainForm.btnReportClick(Sender: TObject);
begin
  ShellExecute(0,'open',pointer(ChangeFileExt(paramstr(0),'.htm')),'','',SW_SHOWMAXIMIZED);
end;

end.






|







 







<







|







 







|







 







|
|







 







|



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
...
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
...
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
...
920
921
922
923
924
925
926
927
928
929
930
    property ReadAllDirectTime: RawUTF8 read fReadAllDirectTime;
    property ReadAllDirectRate: integer read fReadAllDirectRate;
    property ClientCloseTime: RawUTF8 read fClientCloseTime;
  end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  Ini := StringFromFile(ChangeFileExt(ExeVersion.ProgramFileName,'.ini'));
  OraTNSName.Text := UTF8ToString(FindIniEntry(Ini,'Oracle','TNSName'));
  OraUser.Text := UTF8ToString(FindIniEntry(Ini,'Oracle','User'));
  OraPass.Text := UTF8ToString(FindIniEntry(Ini,'Oracle','Password'));
  Stats := TObjectList.Create;
end;

const
................................................................................
  FIREBIRD_LIB = 'Firebird'+{$ifdef CPU64}'64'+{$endif=}'\fbembed.dll';

procedure TMainForm.BtnRunTestsClick(Sender: TObject);
var T,U,P: RawUTF8;
    props: TSQLDBSQLite3ConnectionProperties;
    server: TSQLDBServerAbstract;
begin

  //SynDBLog.Family.Level := LOG_VERBOSE;  // for debugging
  T := StringToUTF8(OraTNSName.Text);
  U := StringToUTF8(OraUser.Text);
  P := StringToUTF8(OraPass.Text);
  UpdateIniEntry(Ini,'Oracle','TNSName',T);
  UpdateIniEntry(Ini,'Oracle','User',U);
  UpdateIniEntry(Ini,'Oracle','Password',P);
  FileFromString(Ini,ChangeFileExt(ExeVersion.ProgramFileName,'.ini'));
  LogMemo.Clear;
{  FreeAndNil(sqlite3); sqlite3 := TSQLite3LibraryDynamic.Create('sqlite3.dll'); }
  // if false then
  try
  try
    // -------- SQlite3
    //(*
................................................................................
  except
    on E: Exception do
      LogMemo.Lines.Add(E.Message);
  end;
  finally
    Label3.Caption := '';
    T := ObjectToJSON(Stats,[woHumanReadable]);
    FileFromString(T,ChangeFileExt(ExeVersion.ProgramFileName,'.stats'));
    FileFromString(T,Ansi7ToString(NowToString(false))+'.log');
    SaveStats;
  end;
end;

type
  TSQLRecordSample = class(TSQLRecord)
................................................................................
  for i := 0 to Stats.Count-1 do
    txt := txt+Int32ToUtf8(Stat[i].ReadAllVirtualRate)+',';
  txt[length(txt)] := '|';
  for i := 0 to Stats.Count-1 do
    txt := txt+Int32ToUtf8(Stat[i].ReadAllDirectRate)+',';
  PicEnd(Cat1);

  FileFromString(Doc,ChangeFileExt(ExeVersion.ProgramFileName,'.txt'));
  FileFromString('<html><body>'#13#10+s,ChangeFileExt(ExeVersion.ProgramFileName,'.htm'));
end;

procedure TMainForm.FormShow(Sender: TObject);
var Valid: boolean;
    S: RawUTF8;
begin
  btnReport.Visible := DebugHook=0;
................................................................................
    SaveStats;
  Close;
end;


procedure TMainForm.btnReportClick(Sender: TObject);
begin
  ShellExecute(0,'open',pointer(ChangeFileExt(ExeVersion.ProgramFileName,'.htm')),'','',SW_SHOWMAXIMIZED);
end;

end.

Changes to SQLite3/Samples/16 - Execute SQL via services/Project16ClientMain.pas.

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
  fSettings.Free;
end;

procedure TMainForm.FormShow(Sender: TObject);
begin
  PTypeInfo(TypeInfo(TRemoteSQLEngine))^.EnumBaseType^.AddCaptionStrings(cbbEngine.Items);
  fSettings := TProjectSettings.Create;
  fSettingsFileName := ChangeFileExt(paramstr(0),'.settings');
  JSONFileToObject(fSettingsFileName,fSettings);
  cbbEngine.ItemIndex := ord(fSettings.fEngine);
  lbledtServer.Text := UTF8ToString(fSettings.fServerName);
  lbledtDatabase.Text := UTF8ToString(fSettings.fDatabaseName);
  lbledtUser.Text := UTF8ToString(fSettings.fUserID);
  lbledtPassword.Text := UTF8ToString(fSettings.fPassword);
  fModel := TSQLModel.Create([],ROOT_NAME);






|







88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
  fSettings.Free;
end;

procedure TMainForm.FormShow(Sender: TObject);
begin
  PTypeInfo(TypeInfo(TRemoteSQLEngine))^.EnumBaseType^.AddCaptionStrings(cbbEngine.Items);
  fSettings := TProjectSettings.Create;
  fSettingsFileName := ChangeFileExt(ExeVersion.ProgramFileName,'.settings');
  JSONFileToObject(fSettingsFileName,fSettings);
  cbbEngine.ItemIndex := ord(fSettings.fEngine);
  lbledtServer.Text := UTF8ToString(fSettings.fServerName);
  lbledtDatabase.Text := UTF8ToString(fSettings.fDatabaseName);
  lbledtUser.Text := UTF8ToString(fSettings.fUserID);
  lbledtPassword.Text := UTF8ToString(fSettings.fPassword);
  fModel := TSQLModel.Create([],ROOT_NAME);

Changes to SQLite3/Samples/21 - HTTP Client-Server performance/Project21HttpServer.dpr.

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    Level := LOG_STACKTRACE;
    EchoToConsole := LOG_VERBOSE; // events to the console
    PerThreadLog := ptIdentifiedInOnFile;
  end;
  // create a Data Model
  aModel := TSQLModel.Create([TSQLRecordPeople]);
  try
    aDatabaseFile := ChangeFileExt(paramstr(0),'.db3');
    DeleteFile(aDatabaseFile);
    aServer := TSQLRestServerDB.Create(aModel,aDatabaseFile);
    try
      aServer.AcquireWriteTimeOut := 15000;   // 15 seconds before write failure
      aServer.DB.Synchronous := smOff;
      aServer.DB.LockingMode := lmExclusive;  // off+exclusive = fastest SQLite3  
      aServer.NoAJAXJSON := true;






|







41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    Level := LOG_STACKTRACE;
    EchoToConsole := LOG_VERBOSE; // events to the console
    PerThreadLog := ptIdentifiedInOnFile;
  end;
  // create a Data Model
  aModel := TSQLModel.Create([TSQLRecordPeople]);
  try
    aDatabaseFile := ChangeFileExt(ExeVersion.ProgramFileName,'.db3');
    DeleteFile(aDatabaseFile);
    aServer := TSQLRestServerDB.Create(aModel,aDatabaseFile);
    try
      aServer.AcquireWriteTimeOut := 15000;   // 15 seconds before write failure
      aServer.DB.Synchronous := smOff;
      aServer.DB.LockingMode := lmExclusive;  // off+exclusive = fastest SQLite3  
      aServer.NoAJAXJSON := true;

Changes to SQLite3/Samples/22 - JavaScript HTTPApi web server/JSHttpApiServer.dpr.

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
...
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
  end;


{ TTestServer }

constructor TTestServer.Create(const Path: TFileName);
begin
  ExeVersionRetrieve; 
  fServer := THttpApiServer.Create(false);
  fSMManager := TSMEngineManager.Create;
  fSMManager.OnNewEngine := DoOnNewEngine;
  fShowDownLib := AnyTextFileToSynUnicode(ExeVersion.ProgramFilePath+'showdown.js');
  fServer.AddUrl('root','888',false,'+',true);
  fServer.RegisterCompress(CompressDeflate); // our server will deflate html :)
  fServer.OnRequest := Process;
................................................................................
      // THttpApiServer.Execute will return 404 if not found
    end;
    result := 200;
  end;
end;

begin
  with TTestServer.Create(ExtractFilePath(ParamStr(0))) do
  try
    write('Server is now running on http://localhost:888/root'#13#10#13#10+
      'Press [Enter] to quit');
    readln;
  finally
    Free;
  end;
  
{$endif WIN64}
end.







<







 







|











53
54
55
56
57
58
59

60
61
62
63
64
65
66
...
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
  end;


{ TTestServer }

constructor TTestServer.Create(const Path: TFileName);
begin

  fServer := THttpApiServer.Create(false);
  fSMManager := TSMEngineManager.Create;
  fSMManager.OnNewEngine := DoOnNewEngine;
  fShowDownLib := AnyTextFileToSynUnicode(ExeVersion.ProgramFilePath+'showdown.js');
  fServer.AddUrl('root','888',false,'+',true);
  fServer.RegisterCompress(CompressDeflate); // our server will deflate html :)
  fServer.OnRequest := Process;
................................................................................
      // THttpApiServer.Execute will return 404 if not found
    end;
    result := 200;
  end;
end;

begin
  with TTestServer.Create(ExeVersion.ProgramFilePath) do
  try
    write('Server is now running on http://localhost:888/root'#13#10#13#10+
      'Press [Enter] to quit');
    readln;
  finally
    Free;
  end;
  
{$endif WIN64}
end.

Changes to SQLite3/Samples/23 - JavaScript Tests/SynSMSelfTest.pas.

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
....
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
....
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
  ansiScriptStrConcatUndefPlusNum: AnsiString = '''fuck me tender '' + (undefined + 1)';
var
  scrObj: PJSScript;
  rval: jsval;
//  fn: AnsiString;
  uString: SynUnicode;
begin
  scriptDir := ExtractFilePath(ParamStr(0)) + 'js';
  Check(DirectoryExists(scriptDir), scriptDir + ' dose not exist');
  if CheckFailed(IsAnsiCompatible(PChar(scriptDir)), ' Path to test directory must be Ansi Compatible') then Exit;

  // check global accessible from script
  Check( JS_EvaluateScript(cx, global, PCChar(globalAccess), length(globalAccess), 'test', 1, rval) = JS_TRUE, 'direct assign global.var');

  // check error, which was in SM17
................................................................................
  engine: TSMEngine;
  mSource: SynUnicode;
  mustacheFN: TFileName;
  mustache: RawByteString;
  i: integer;
begin
  engine := FManager.ThreadSafeEngine;
  mustacheFN := ExtractFilePath(ParamStr(0)) + 'js\mustache.js';
  mSource := AnyTextFileToSynUnicode(mustacheFN);
  if mSource='' then begin
    mustache := TWinINet.Get('https://github.com/janl/mustache.js/raw/master/mustache.js');
    if PosEx('return send(result);',mustache)=0 then begin
      i := PosEx('send(result);',mustache);
      if i>0 then
        insert('return ',mustache,i); // fix syntax error in official libary! :)
................................................................................
  mSource: SynUnicode;
  inArr: SMValArray;
  outv: TSMValue;
  i: Integer;
  resultFromFortunes, rendered: RawUTF8; // n frtune test here must be resultFromFortunes of database query
begin
  engine := FManager.ThreadSafeEngine;
  mSource := AnyTextFileToSynUnicode(ExtractFilePath(ParamStr(0)) + 'js\precompiledMustache.js');
  if mSource='' then
    exit;
  CheckFailed(mSource <> '', 'exist js\precompiledMustache.js');
  engine.Evaluate(mSource, 'precompiledMustache.js');
  setLength(inArr, 1);
  for i := 0 to 1000 do begin
    resultFromFortunes := FormatUTF8('[{"id": %, "message": "message%"},{"id": %, "message": "message%"}]', [i, i, i+1, i+1]);






|







 







|







 







|







252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
....
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
....
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
  ansiScriptStrConcatUndefPlusNum: AnsiString = '''fuck me tender '' + (undefined + 1)';
var
  scrObj: PJSScript;
  rval: jsval;
//  fn: AnsiString;
  uString: SynUnicode;
begin
  scriptDir := ExeVersion.ProgramFilePath + 'js';
  Check(DirectoryExists(scriptDir), scriptDir + ' dose not exist');
  if CheckFailed(IsAnsiCompatible(PChar(scriptDir)), ' Path to test directory must be Ansi Compatible') then Exit;

  // check global accessible from script
  Check( JS_EvaluateScript(cx, global, PCChar(globalAccess), length(globalAccess), 'test', 1, rval) = JS_TRUE, 'direct assign global.var');

  // check error, which was in SM17
................................................................................
  engine: TSMEngine;
  mSource: SynUnicode;
  mustacheFN: TFileName;
  mustache: RawByteString;
  i: integer;
begin
  engine := FManager.ThreadSafeEngine;
  mustacheFN := ExeVersion.ProgramFilePath + 'js\mustache.js';
  mSource := AnyTextFileToSynUnicode(mustacheFN);
  if mSource='' then begin
    mustache := TWinINet.Get('https://github.com/janl/mustache.js/raw/master/mustache.js');
    if PosEx('return send(result);',mustache)=0 then begin
      i := PosEx('send(result);',mustache);
      if i>0 then
        insert('return ',mustache,i); // fix syntax error in official libary! :)
................................................................................
  mSource: SynUnicode;
  inArr: SMValArray;
  outv: TSMValue;
  i: Integer;
  resultFromFortunes, rendered: RawUTF8; // n frtune test here must be resultFromFortunes of database query
begin
  engine := FManager.ThreadSafeEngine;
  mSource := AnyTextFileToSynUnicode(ExeVersion.ProgramFilePath + 'js\precompiledMustache.js');
  if mSource='' then
    exit;
  CheckFailed(mSource <> '', 'exist js\precompiledMustache.js');
  engine.Evaluate(mSource, 'precompiledMustache.js');
  setLength(inArr, 1);
  for i := 0 to 1000 do begin
    resultFromFortunes := FormatUTF8('[{"id": %, "message": "message%"},{"id": %, "message": "message%"}]', [i, i, i+1, i+1]);

Changes to SQLite3/Samples/23 - JavaScript Tests/TestMustacheUnit.pas.

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
...
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
      result := VariantToUTF8(fEngine.Global.Mustache.render(Template, data, partial));
  end else
  {$endif}
    exit;
  mmoResult.Lines.Text :=
    Format('Rendered %d times in %s (%d/sec):'#13#10#13#10'%s',
      [n,Timer.Stop,Timer.PerSec(n),result]);
  FileFromString(Result,ChangeFileExt(paramstr(0),'.html'));
end;

procedure TMainForm.btnOpenBrowserClick(Sender: TObject);
begin
  ShellExecute(0,'open',Pointer(ChangeFileExt(paramstr(0),'.html')),nil,nil,SW_SHOWNORMAL);
end;

procedure TMainForm.FormShow(Sender: TObject);
{$ifdef CPU64} // SpiderMonkey library is not available yet in 64 bit
begin
  btnExecSpiderMonkey.Hide;
end;
................................................................................
var mustacheFN: TFileName;
    mSource: SynUnicode;
    mustache: RawByteString;
    i: integer;
begin
  fEngineManager := TSMEngineManager.Create;
  fEngine := fEngineManager.ThreadSafeEngine;
  mustacheFN := ExtractFilePath(ParamStr(0)) + 'js\mustache.js';
  mSource := AnyTextFileToSynUnicode(mustacheFN);
  if mSource='' then begin
    mustache := TWinINet.Get('https://github.com/janl/mustache.js/raw/master/mustache.js');
    if PosEx('return send(result);',mustache)=0 then begin
      i := PosEx('send(result);',mustache);
      if i>0 then
        insert('return ',mustache,i); // fix syntax error in official libary! :)






|




|







 







|







90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
...
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
      result := VariantToUTF8(fEngine.Global.Mustache.render(Template, data, partial));
  end else
  {$endif}
    exit;
  mmoResult.Lines.Text :=
    Format('Rendered %d times in %s (%d/sec):'#13#10#13#10'%s',
      [n,Timer.Stop,Timer.PerSec(n),result]);
  FileFromString(Result,ChangeFileExt(ExeVersion.ProgramFileName,'.html'));
end;

procedure TMainForm.btnOpenBrowserClick(Sender: TObject);
begin
  ShellExecute(0,'open',Pointer(ChangeFileExt(ExeVersion.ProgramFileName,'.html')),nil,nil,SW_SHOWNORMAL);
end;

procedure TMainForm.FormShow(Sender: TObject);
{$ifdef CPU64} // SpiderMonkey library is not available yet in 64 bit
begin
  btnExecSpiderMonkey.Hide;
end;
................................................................................
var mustacheFN: TFileName;
    mSource: SynUnicode;
    mustache: RawByteString;
    i: integer;
begin
  fEngineManager := TSMEngineManager.Create;
  fEngine := fEngineManager.ThreadSafeEngine;
  mustacheFN := ExeVersion.ProgramFilePath + 'js\mustache.js';
  mSource := AnyTextFileToSynUnicode(mustacheFN);
  if mSource='' then begin
    mustache := TWinINet.Get('https://github.com/janl/mustache.js/raw/master/mustache.js');
    if PosEx('return send(result);',mustache)=0 then begin
      i := PosEx('send(result);',mustache);
      if i>0 then
        insert('return ',mustache,i); // fix syntax error in official libary! :)

Changes to SQLite3/Samples/25 - JSON performance/JSONPerfTestCases.pas.

909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
....
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
{ TTestBigContentRead }

procedure TTestBigContentRead.DownloadFilesIfNecessary;
var download: RawByteString;
begin // overriden method should have been set fFileName+fZipFileName+fDownloadURI
  fRunConsoleOccurenceNumber := 0;
  fMemoryAtStart := MemoryUsed;
  fFileName := ExtractFilePath(ParamStr(0))+fFileName;
  if not FileExists(fFileName) then begin
    download := TWinINet.Get(fDownloadURI);
    if not CheckFailed(download<>'') then begin
      with TZipRead.Create(pointer(download),length(download)) do
      try
        UnZip(fZipFileName,fFileName,true);
      finally
................................................................................
    property YearOfDeath: word read fYearOfDeath write fYearOfDeath;
  end;

procedure TTestTableContent.DownloadFilesIfNecessary;
var i: integer;
begin
  fMemoryAtStart := MemoryUsed;
  fFileName := ExtractFilePath(paramstr(0));
  i := pos('\Samples\',fFileName);
  if i>0 then begin
    Setlength(fFileName,i);
    if FileExists(fFileName+'exe\people.json') then
      fFileName := fFileName+'exe\people.json' else
      fFileName  := fFileName+'people.json'
  end;






|







 







|







909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
....
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
{ TTestBigContentRead }

procedure TTestBigContentRead.DownloadFilesIfNecessary;
var download: RawByteString;
begin // overriden method should have been set fFileName+fZipFileName+fDownloadURI
  fRunConsoleOccurenceNumber := 0;
  fMemoryAtStart := MemoryUsed;
  fFileName := ExeVersion.ProgramFilePath+fFileName;
  if not FileExists(fFileName) then begin
    download := TWinINet.Get(fDownloadURI);
    if not CheckFailed(download<>'') then begin
      with TZipRead.Create(pointer(download),length(download)) do
      try
        UnZip(fZipFileName,fFileName,true);
      finally
................................................................................
    property YearOfDeath: word read fYearOfDeath write fYearOfDeath;
  end;

procedure TTestTableContent.DownloadFilesIfNecessary;
var i: integer;
begin
  fMemoryAtStart := MemoryUsed;
  fFileName := ExeVersion.ProgramFilePath;
  i := pos('\Samples\',fFileName);
  if i>0 then begin
    Setlength(fFileName,i);
    if FileExists(fFileName+'exe\people.json') then
      fFileName := fFileName+'exe\people.json' else
      fFileName  := fFileName+'people.json'
  end;

Changes to SQLite3/Samples/26 - RESTful ORM/RESTserver.dpr.

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  mORMotHTTPServer,
  RESTData,
  RESTServerClass in 'RESTServerClass.pas';

var ORMServer: TNoteServer;
    HTTPServer: TSQLHttpServer;
begin
  ORMServer := TNoteServer.Create(ExtractFilePath(paramstr(0))+'data','root');
  try
    HTTPServer := TSQLHttpServer.Create(HTTP_PORT,[ORMServer]);
    try
      AllocConsole;
      TSQLLog.Family.EchoToConsole := LOG_VERBOSE;
      writeln(#13#10'Background server is running at http://localhost:888'#13#10+
              #13#10'Press [Enter] to close the server.');






|







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  mORMotHTTPServer,
  RESTData,
  RESTServerClass in 'RESTServerClass.pas';

var ORMServer: TNoteServer;
    HTTPServer: TSQLHttpServer;
begin
  ORMServer := TNoteServer.Create(ExeVersion.ProgramFilePath+'data','root');
  try
    HTTPServer := TSQLHttpServer.Create(HTTP_PORT,[ORMServer]);
    try
      AllocConsole;
      TSQLLog.Family.EchoToConsole := LOG_VERBOSE;
      writeln(#13#10'Background server is running at http://localhost:888'#13#10+
              #13#10'Press [Enter] to close the server.');

Changes to SQLite3/Samples/30 - MVC Server/MVCModel.pas.

468
469
470
471
472
473
474

475
476
477
478
479
480
481
482
483
484
485
...
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
...
583
584
585
586
587
588
589

      while P^<>' ' do
        if P^=#0 then
          break else
          inc(P);
      if P^=#0 then
        break;
      inc(P);

      if IdemPChar(P,'HREF=') then
        H := P+5 else
      if IdemPChar(P,'SRC=') then
        H := P+4 else
        continue;
      if H^='"' then inc(H);
      AddNoJSONEscape(B,H-B);
      P := H;
      if P^='/' then
        if IdemPChar(P+1,'POST/') then begin
          GetUrl(P+6);
................................................................................
            inc(P,urlLen+6);
          end else
            AddString(aDotClearRoot);
        end else
        if IdemPChar(P+1,'PUBLIC/') then begin
          if PublicFolder<>'' then begin
            GetUrl(P+8);
            FN := PublicFolder+UTF8ToString(StringReplaceChars(url,'/','\'));
            EnsureDirectoryExists(ExtractFilePath(FN));
            if not FileExists(FN) then

              FileFromString(TWinHTTP.Get(aDotClearRoot+'/public/'+url),FN);
            AddShort('.static');
          end else
            AddString(aDotClearRoot);
        end;
      B := P;
    end;
    AddNoJSONEscape(B);
................................................................................
    SetText(result);
  finally
    Free;
  end;
end;
begin
  if aStaticFolder<>'' then begin
    PublicFolder := IncludeTrailingPathDelimiter(aStaticFolder)+'public\';
    EnsureDirectoryExists(PublicFolder);
  end;
  TAutoFree.Several([
    @data,TDotClearTable.Parse(aFlatFile),
    @urls,TRawUTF8ListHashed.Create,
    @batch,TSQLRestBatch.Create(Rest,TSQLTag,5000)]);
  TSQLRecord.AutoFree([ // avoid several try..finally
................................................................................
  end;
  Rest.BatchSend(batch);
  aTagsLookup.SaveOccurence(Rest);
end;


end.







>

|

|







 







|


>
|







 







|







 







>
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
...
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
...
585
586
587
588
589
590
591
592
      while P^<>' ' do
        if P^=#0 then
          break else
          inc(P);
      if P^=#0 then
        break;
      inc(P);
      H := P; // makes compiler happy
      if IdemPChar(P,'HREF=') then
        inc(H,5) else
      if IdemPChar(P,'SRC=') then
        inc(H,4) else
        continue;
      if H^='"' then inc(H);
      AddNoJSONEscape(B,H-B);
      P := H;
      if P^='/' then
        if IdemPChar(P+1,'POST/') then begin
          GetUrl(P+6);
................................................................................
            inc(P,urlLen+6);
          end else
            AddString(aDotClearRoot);
        end else
        if IdemPChar(P+1,'PUBLIC/') then begin
          if PublicFolder<>'' then begin
            GetUrl(P+8);
            FN := PublicFolder+UTF8ToString(StringReplaceChars(url,'/',PathDelim));
            EnsureDirectoryExists(ExtractFilePath(FN));
            if not FileExists(FN) then
              FileFromString({$ifdef MSWINDOWS}TWinHTTP.Get{$else}HttpGet{$endif}(
                aDotClearRoot+'/public/'+url),FN);
            AddShort('.static');
          end else
            AddString(aDotClearRoot);
        end;
      B := P;
    end;
    AddNoJSONEscape(B);
................................................................................
    SetText(result);
  finally
    Free;
  end;
end;
begin
  if aStaticFolder<>'' then begin
    PublicFolder := IncludeTrailingPathDelimiter(aStaticFolder)+'public'+PathDelim;
    EnsureDirectoryExists(PublicFolder);
  end;
  TAutoFree.Several([
    @data,TDotClearTable.Parse(aFlatFile),
    @urls,TRawUTF8ListHashed.Create,
    @batch,TSQLRestBatch.Create(Rest,TSQLTag,5000)]);
  TSQLRecord.AutoFree([ // avoid several try..finally
................................................................................
  end;
  Rest.BatchSend(batch);
  aTagsLookup.SaveOccurence(Rest);
end;


end.

Changes to SQLite3/Samples/30 - MVC Server/MVCServer.dpr.

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var aModel: TSQLModel;
    aServer: TSQLRestServerDB;
    aApplication: TBlogApplication;
    aHTTPServer: TSQLHttpServer;
begin
  aModel := CreateModel;
  try
    aServer := TSQLRestServerDB.Create(aModel,ChangeFileExt(paramstr(0),'.db'));
    try
      aServer.DB.Synchronous := smNormal;
      aServer.DB.LockingMode := lmExclusive;
      aServer.CreateMissingTables;
      aApplication := TBlogApplication.Create;
      try
        aApplication.Start(aServer);






|







20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var aModel: TSQLModel;
    aServer: TSQLRestServerDB;
    aApplication: TBlogApplication;
    aHTTPServer: TSQLHttpServer;
begin
  aModel := CreateModel;
  try
    aServer := TSQLRestServerDB.Create(aModel,ChangeFileExt(ExeVersion.ProgramFileName,'.db'));
    try
      aServer.DB.Synchronous := smNormal;
      aServer.DB.LockingMode := lmExclusive;
      aServer.CreateMissingTables;
      aApplication := TBlogApplication.Create;
      try
        aApplication.Start(aServer);

Changes to SQLite3/Samples/MainDemo/FileServer.pas.

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
      fTempAuditTrail.StatusMessage := T.RecordProps.SQLTableName+'  '+tmp;
    end;
  Add(fTempAuditTrail,true);
end;

constructor TFileServer.Create;
begin
  inherited Create(CreateFileModel(self),ChangeFileExt(paramstr(0),'.db3'));
  CreateMissingTables(ExeVersion.Version.Version32);
  Server := TSQLHttpServer.Create(SERVER_HTTP_PORT,self,'+',useHttpApiRegisteringURI);
  AddAuditTrail(feServerStarted);
  OnUpdateEvent := OnDatabaseUpdateEvent;
end;

destructor TFileServer.Destroy;






|







70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
      fTempAuditTrail.StatusMessage := T.RecordProps.SQLTableName+'  '+tmp;
    end;
  Add(fTempAuditTrail,true);
end;

constructor TFileServer.Create;
begin
  inherited Create(CreateFileModel(self),ChangeFileExt(ExeVersion.ProgramFileName,'.db3'));
  CreateMissingTables(ExeVersion.Version.Version32);
  Server := TSQLHttpServer.Create(SERVER_HTTP_PORT,self,'+',useHttpApiRegisteringURI);
  AddAuditTrail(feServerStarted);
  OnUpdateEvent := OnDatabaseUpdateEvent;
end;

destructor TFileServer.Destroy;

Changes to SQLite3/Samples/MainDemo/FileTables.pas.

199
200
201
202
203
204
205
206
207
208

209
function CreateFileModel(Owner: TSQLRest): TSQLModel;
begin
  result := TSQLModel.Create(Owner,
    @FileTabs,length(FileTabs),sizeof(FileTabs[0]),[],
    TypeInfo(TFileAction),TypeInfo(TFileEvent));
end;


initialization
  ExeVersionRetrieve(3);

end.






<

<
>

199
200
201
202
203
204
205

206

207
208
function CreateFileModel(Owner: TSQLRest): TSQLModel;
begin
  result := TSQLModel.Create(Owner,
    @FileTabs,length(FileTabs),sizeof(FileTabs[0]),[],
    TypeInfo(TFileAction),TypeInfo(TFileEvent));
end;


initialization

  SetExecutableVersion(3,0,0);
end.

Changes to SQLite3/TestOleDB.dpr.

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    //Props.ConnectionStringDialogExecute;
    Conn := Props.NewConnection;
    try
      Conn.Connect; // optional
      Query := Conn.NewStatement;
      try
        Query.Execute('select * from Sales.Customer where AccountNumber like ?',true,['AW000001%']);
        F := TFileStream.Create(ChangeFileExt(paramstr(0),'.json'),fmCreate);
        try
          Query.FetchAllToJSON(F,false);
        finally
          F.Free;
        end;
      finally
        Query.Free;






|







56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    //Props.ConnectionStringDialogExecute;
    Conn := Props.NewConnection;
    try
      Conn.Connect; // optional
      Query := Conn.NewStatement;
      try
        Query.Execute('select * from Sales.Customer where AccountNumber like ?',true,['AW000001%']);
        F := TFileStream.Create(ChangeFileExt(ExeVersion.ProgramFileName,'.json'),fmCreate);
        try
          Query.FetchAllToJSON(F,false);
        finally
          F.Free;
        end;
      finally
        Query.Free;

Changes to SQLite3/TestSQL3.dpr.

172
173
174
175
176
177
178
179
180
181
182
183
184
  {$ifdef ISDELPHI2007ANDUP}
  {$ifdef DEBUG}
  ReportMemoryLeaksOnShutdown := True;
  {$endif}
  {$endif}
  SQLite3ConsoleTests;
  {$ifdef COMPUTEFPCINTERFACES}
  ChDir(ExtractFilePath(ParamStr(0)));
  ComputeFPCInterfacesUnit(
    ['..\CrossPlatform\templates','..\..\CrossPlatform\templates'],
     '\..\..\SQlite3\TestSQL3FPCInterfaces.pas');
  {$endif}
end.






|





172
173
174
175
176
177
178
179
180
181
182
183
184
  {$ifdef ISDELPHI2007ANDUP}
  {$ifdef DEBUG}
  ReportMemoryLeaksOnShutdown := True;
  {$endif}
  {$endif}
  SQLite3ConsoleTests;
  {$ifdef COMPUTEFPCINTERFACES}
  ChDir(ExeVersion.ProgramFilePath);
  ComputeFPCInterfacesUnit(
    ['..\CrossPlatform\templates','..\..\CrossPlatform\templates'],
     '\..\..\SQlite3\TestSQL3FPCInterfaces.pas');
  {$endif}
end.

Changes to SQLite3/mORMot.pas.

29207
29208
29209
29210
29211
29212
29213

29214
29215
29216
29217
29218
29219
29220
29221
29222
.....
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
.....
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
.....
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
.....
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
  end;
  if (high(FieldNames)=0) and IsRowID(pointer(FieldNames[0])) then begin
    result := true; // SQLite3 has always its ID/RowID primary key indexed
    exit;
  end;
  Props := Model.TableProps[TableIndex].Props;
  for i := 0 to high(FieldNames) do

    if Props.Fields.IndexByName(FieldNames[i])<0 then
      exit; // wrong field name
  if Unique then
    SQL := 'UNIQUE ' else
    SQL := '';
  if IndexName='' then begin
    IndexName := RawUTF8ArrayToCSV(FieldNames,'');
    if length(IndexName)+length(Props.SQLTableName)>64 then
      // avoid reaching potential identifier name size limit 
................................................................................
  fInputCookieLastName := ''; // cache reset
end;

function TSQLRestServerURIContext.GetResourceFileName: TFileName;
begin
  if (URIBlobFieldName='') or (PosEx('..',URIBlobFieldName)>0) then
    result := '' else // for security, disallow .. in the supplied file path
    result := UTF8ToString(StringReplaceAll(URIBlobFieldName,'/','\'));
end;

procedure TSQLRestServerURIContext.Returns(const Result: RawUTF8;
  Status: integer; const CustomHeader: RawUTF8;
  Handle304NotModified,HandleErrorAsRegularResult: boolean);
var clientHash, serverHash: RawUTF8;
begin
................................................................................
  const Error404Redirect: RawUTF8);
var fileName: TFileName;
begin
  if URIBlobFieldName='' then
    fileName := DefaultFileName else
    if PosEx('..',URIBlobFieldName)>0 then
      fileName := '' else
      fileName := UTF8ToString(StringReplaceChars(URIBlobFieldName,'/','\'));
  if fileName<>'' then
    fileName := IncludeTrailingPathDelimiter(FolderName)+fileName;
  ReturnFile(fileName,Handle304NotModified,'','',Error404Redirect);
end;

procedure TSQLRestServerURIContext.Redirect(const NewLocation: RawUTF8;
  PermanentChange: boolean);
................................................................................
    fFeatures.FileExtension := UTF8ToString(LowerCase(fModuleName));
end;

function TSQLVirtualTableModule.FileName(const aTableName: RawUTF8): TFileName;
begin
  result := UTF8ToString(aTableName)+'.'+FileExtension;;
  if fFilePath='' then
    result := ExtractFilePath(paramstr(0))+result else
    result := IncludeTrailingPathDelimiter(fFilePath)+result;
end;


{ TSQLVirtualTable }

constructor TSQLVirtualTable.Create(aModule: TSQLVirtualTableModule;
................................................................................
  pointer(@SQLFieldTypeComp[sftObject]) := @StrComp;
{$ifndef NOVARIANTS}
  pointer(@SQLFieldTypeComp[sftVariant]) := @StrComp;
{$endif}
{$ifndef USENORMTOUPPER}
  pointer(@SQLFieldTypeComp[sftUTF8Text]) := @AnsiIComp;
{$endif}
  {$ifdef MSWINDOWS}
  ExeVersionRetrieve; // the sooner the better
  {$endif}
  SetCurrentThreadName('Main thread',[]);
  TTextWriter.SetDefaultJSONClass(TJSONSerializer);
  assert(sizeof(TServiceMethod)and 3=0,'wrong padding');
end.










>
|
|







 







|







 







|







 







|







 







<
<
<








29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
.....
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
.....
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
.....
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
.....
43162
43163
43164
43165
43166
43167
43168



43169
43170
43171
43172
43173
43174
43175
43176
  end;
  if (high(FieldNames)=0) and IsRowID(pointer(FieldNames[0])) then begin
    result := true; // SQLite3 has always its ID/RowID primary key indexed
    exit;
  end;
  Props := Model.TableProps[TableIndex].Props;
  for i := 0 to high(FieldNames) do
    if not IsRowID(pointer(FieldNames[i])) then
      if (Props.Fields.IndexByName(FieldNames[i])<0) then
        exit; // wrong field name
  if Unique then
    SQL := 'UNIQUE ' else
    SQL := '';
  if IndexName='' then begin
    IndexName := RawUTF8ArrayToCSV(FieldNames,'');
    if length(IndexName)+length(Props.SQLTableName)>64 then
      // avoid reaching potential identifier name size limit 
................................................................................
  fInputCookieLastName := ''; // cache reset
end;

function TSQLRestServerURIContext.GetResourceFileName: TFileName;
begin
  if (URIBlobFieldName='') or (PosEx('..',URIBlobFieldName)>0) then
    result := '' else // for security, disallow .. in the supplied file path
    result := UTF8ToString(StringReplaceAll(URIBlobFieldName,'/',PathDelim));
end;

procedure TSQLRestServerURIContext.Returns(const Result: RawUTF8;
  Status: integer; const CustomHeader: RawUTF8;
  Handle304NotModified,HandleErrorAsRegularResult: boolean);
var clientHash, serverHash: RawUTF8;
begin
................................................................................
  const Error404Redirect: RawUTF8);
var fileName: TFileName;
begin
  if URIBlobFieldName='' then
    fileName := DefaultFileName else
    if PosEx('..',URIBlobFieldName)>0 then
      fileName := '' else
      fileName := UTF8ToString(StringReplaceChars(URIBlobFieldName,'/',PathDelim));
  if fileName<>'' then
    fileName := IncludeTrailingPathDelimiter(FolderName)+fileName;
  ReturnFile(fileName,Handle304NotModified,'','',Error404Redirect);
end;

procedure TSQLRestServerURIContext.Redirect(const NewLocation: RawUTF8;
  PermanentChange: boolean);
................................................................................
    fFeatures.FileExtension := UTF8ToString(LowerCase(fModuleName));
end;

function TSQLVirtualTableModule.FileName(const aTableName: RawUTF8): TFileName;
begin
  result := UTF8ToString(aTableName)+'.'+FileExtension;;
  if fFilePath='' then
    result := ExeVersion.ProgramFilePath+result else
    result := IncludeTrailingPathDelimiter(fFilePath)+result;
end;


{ TSQLVirtualTable }

constructor TSQLVirtualTable.Create(aModule: TSQLVirtualTableModule;
................................................................................
  pointer(@SQLFieldTypeComp[sftObject]) := @StrComp;
{$ifndef NOVARIANTS}
  pointer(@SQLFieldTypeComp[sftVariant]) := @StrComp;
{$endif}
{$ifndef USENORMTOUPPER}
  pointer(@SQLFieldTypeComp[sftUTF8Text]) := @AnsiIComp;
{$endif}



  SetCurrentThreadName('Main thread',[]);
  TTextWriter.SetDefaultJSONClass(TJSONSerializer);
  assert(sizeof(TServiceMethod)and 3=0,'wrong padding');
end.




Changes to SQLite3/mORMotDDD.pas.

777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
    a,i,f: integer;
    code,aggname,recname,parentrecname: RawUTF8;
    map: TSQLPropInfoList;
    rectypes: TRawUTF8DynArray;
begin
  {$ifdef KYLIX3} hier := nil; {$endif to make compiler happy}
  if DestinationSourceCodeFile='' then
    DestinationSourceCodeFile := ExtractFilePath(paramstr(0))+'ddsqlrecord.inc';
  for a := 0 to high(aAggregate) do begin
    hier := ClassHierarchyWithField(aAggregate[a]);
    code := code+#13#10'type';
    parentrecname := 'TSQLRecord';
    for i := 0 to high(hier) do begin
      aggname := RawUTF8(hier[i].ClassName);
      recname := 'TSQLRecord'+copy(aggname,2,100);






|







777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
    a,i,f: integer;
    code,aggname,recname,parentrecname: RawUTF8;
    map: TSQLPropInfoList;
    rectypes: TRawUTF8DynArray;
begin
  {$ifdef KYLIX3} hier := nil; {$endif to make compiler happy}
  if DestinationSourceCodeFile='' then
    DestinationSourceCodeFile := ExeVersion.ProgramFilePath+'ddsqlrecord.inc';
  for a := 0 to high(aAggregate) do begin
    hier := ClassHierarchyWithField(aAggregate[a]);
    code := code+#13#10'type';
    parentrecname := 'TSQLRecord';
    for i := 0 to high(hier) do begin
      aggname := RawUTF8(hier[i].ClassName);
      recname := 'TSQLRecord'+copy(aggname,2,100);

Changes to SQLite3/mORMotFastCgiServer.pas.

600
601
602
603
604
605
606
607

608
609
610
611
612
613
614
      flistenType := ltPipeSync else begin
      flistenType := ltSocketSync;
      fSocket := TCrtSocket.Create(5000);
    end;
    exit;
  end;
  // if we reached here, exe was not called as a FastCGI process
  raise Exception.CreateFmt('%s not called as a FastCGI process',[paramstr(0)]);

{$else}
  not implemented yet: please use libfcgi.so version, which seems stable & fast
  under Linux
{$endif}
end;

destructor TFastCGIServer.Destroy;






|
>







600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
      flistenType := ltPipeSync else begin
      flistenType := ltSocketSync;
      fSocket := TCrtSocket.Create(5000);
    end;
    exit;
  end;
  // if we reached here, exe was not called as a FastCGI process
  raise ESynException.CreateUTF8('%.Create: % not called as a FastCGI process',
    [Self,ExeVersion.ProgramFileName]);
{$else}
  not implemented yet: please use libfcgi.so version, which seems stable & fast
  under Linux
{$endif}
end;

destructor TFastCGIServer.Destroy;

Changes to SQLite3/mORMotMVC.pas.

703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
....
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
    info: variant;
    SR: TSearchRec;
begin
  inherited Create(aInterface,aLogClass);
  // get views
  fViewTemplateFileTimestampMonitor := aParameters.FileTimestampMonitorAfterSeconds;
  if aParameters.Folder='' then
    fViewTemplateFolder := ExtractFilePath(ParamStr(0))+'Views\' else
    fViewTemplateFolder := IncludeTrailingPathDelimiter(aParameters.Folder);
  if not DirectoryExists(fViewTemplateFolder) then
    CreateDir(fViewTemplateFolder);
  if aParameters.CSVExtensions='' then
    LowerExt := ',html,json,css,' else
    LowerExt := ','+SysUtils.LowerCase(aParameters.CSVExtensions)+',';
  SetLength(fViews,fFactory.MethodsCount);
................................................................................
     IdemPropNameU(rawMethodName,STATIC_URI) then begin
    // code below will use a local in-memory cache, but would do the same as:
    // Ctxt.ReturnFileFromFolder(fViews.ViewTemplateFolder+STATIC_URI);
    static := fStaticCache.Value(rawFormat,#0);
    if static=#0 then begin
      if PosEx('..',rawFormat)>0 then // avoid injection
        static := '' else begin
        staticFileName := UTF8ToString(StringReplaceChars(rawFormat,'/','\'));
        static := StringFromFile(fViews.ViewTemplateFolder+STATIC_URI+'\'+staticFileName);
        if static<>'' then
          static := GetMimeContentType(nil,0,staticFileName)+#0+static;
      end;
      fStaticCache.Add(rawFormat,static);
    end;
    if static='' then
      Ctxt.Error('',HTML_NOTFOUND) else begin






|







 







|
|







703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
....
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
    info: variant;
    SR: TSearchRec;
begin
  inherited Create(aInterface,aLogClass);
  // get views
  fViewTemplateFileTimestampMonitor := aParameters.FileTimestampMonitorAfterSeconds;
  if aParameters.Folder='' then
    fViewTemplateFolder := ExeVersion.ProgramFilePath+'Views'+PathDelim else
    fViewTemplateFolder := IncludeTrailingPathDelimiter(aParameters.Folder);
  if not DirectoryExists(fViewTemplateFolder) then
    CreateDir(fViewTemplateFolder);
  if aParameters.CSVExtensions='' then
    LowerExt := ',html,json,css,' else
    LowerExt := ','+SysUtils.LowerCase(aParameters.CSVExtensions)+',';
  SetLength(fViews,fFactory.MethodsCount);
................................................................................
     IdemPropNameU(rawMethodName,STATIC_URI) then begin
    // code below will use a local in-memory cache, but would do the same as:
    // Ctxt.ReturnFileFromFolder(fViews.ViewTemplateFolder+STATIC_URI);
    static := fStaticCache.Value(rawFormat,#0);
    if static=#0 then begin
      if PosEx('..',rawFormat)>0 then // avoid injection
        static := '' else begin
        staticFileName := UTF8ToString(StringReplaceChars(rawFormat,'/',PathDelim));
        static := StringFromFile(fViews.ViewTemplateFolder+STATIC_URI+PathDelim+staticFileName);
        if static<>'' then
          static := GetMimeContentType(nil,0,staticFileName)+#0+static;
      end;
      fStaticCache.Add(rawFormat,static);
    end;
    if static='' then
      Ctxt.Error('',HTML_NOTFOUND) else begin

Changes to SQLite3/mORMotSQLite3.pas.

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
...
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
....
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
....
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
....
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
....
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
....
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
....
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
....
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
....
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
....
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
....
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
....
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
....
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
procedure TSQLRestServerDB.GetAndPrepareStatement(const SQL: RawUTF8;
  ForceCacheStatement: boolean);
var i, maxParam,sqlite3param: integer;
    Types: TSQLParamTypeDynArray;
    Nulls: TSQLFieldBits;
    Values: TRawUTF8DynArray;

begin
  fStatementTimer.Start;
  fStatementSQL := SQL;
  fStatementGenericSQL := ExtractInlineParameters(SQL,Types,Values,maxParam,Nulls);
  if (maxParam=0) and not ForceCacheStatement then begin
    // SQL code with no valid :(...): internal parameters
    fStatementGenericSQL := '';
    fStaticStatement.Prepare(DB.DB,SQL);
    fStatement := @fStaticStatement;
    exit;
  end;
  fStatement := fStatementCache.Prepare(fStatementGenericSQL);







  // bind parameters
  sqlite3param := sqlite3.bind_parameter_count(fStatement^.Request);
  if sqlite3param<>maxParam then
    raise EORMException.CreateUTF8(
      '%.GetAndPrepareStatement(%) recognized % params, and % for SQLite3',
      [self,fStatementGenericSQL,maxParam,sqlite3param]);
  for i := 0 to maxParam-1 do
................................................................................
  if fStatement=@fStaticStatement then
    fStaticStatement.Close;
  fStatement := nil;
  fStatementSQL := '';
  fStatementGenericSQL := '';
  if E<>nil then
    fStatementLastException := FormatUTF8('% %',[E,ObjectToJSON(E)]);
end; 

procedure TSQLRestServerDB.FlushStatementCache;
begin
  DB.Lock;
  try
    fStatementCache.ReleaseAllDBStatements;
  finally
................................................................................
      if Res.VText=nil then
       sqlite3.result_text(Context,@NULCHAR,0,SQLITE_STATIC) else
       sqlite3.result_text(Context,Res.VText,-1,SQLITE_TRANSIENT_VIRTUALTABLE);
    ftBlob:
      sqlite3.result_blob(Context,Res.VBlob,Res.VBlobLen,SQLITE_TRANSIENT_VIRTUALTABLE);
    else begin
      {$ifdef WITHLOG}
      SynSQLite3Log.DebuggerNotify(sllWarning,[ord(Res.VType)],'SQLVarToSQlite3Context(%)');
      {$endif}
      result := false; // not handled type
      exit;
    end;
  end;
  result := true;
end;
................................................................................
  SQLITE_BLOB: begin
    Res.VType := ftBlob;
    Res.VBlobLen := sqlite3.value_bytes(Value);
    Res.VBlob := sqlite3.value_blob(Value);
  end;
  else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[ValueType],'SQlite3ValueToSQLVar(%)');
    {$endif}
    Res.VType := ftUnknown;
  end;
  end;
end;

function TSQLVirtualTableModuleSQLite3.FileName(const aTableName: RawUTF8): TFileName;
................................................................................
    ModuleName: RawUTF8;
begin
  if Module<>nil then
    ModuleName := Module.ModuleName;
  if (Module=nil) or (Module.DB.DB<>DB) or
     (StrIComp(pointer(ModuleName),argv[0])<>0) then begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[argv[0],ModuleName],'vt_Create(%<>%)');
    {$endif}
    result := SQLITE_ERROR;
    exit;
  end;
  ppVTab := sqlite3.malloc(sizeof(TSQLite3VTab));
  if ppVTab=nil then begin
    result := SQLITE_NOMEM;
................................................................................
      exit;
    end;
  end;
  Structure := Table.Structure;
  result := sqlite3.declare_vtab(DB,pointer(Structure));
  if result<>SQLITE_OK then begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[ModuleName,Structure],'vt_Create(%) declare_vtab(%)');
    {$endif}
    Table.Free;
    sqlite3.free_(ppVTab);
    result := SQLITE_ERROR;
  end else
    ppVTab^.pInstance := Table;
end;
................................................................................
end;

function vt_Destroy(pVTab: PSQLite3VTab): Integer; {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
begin
  if TSQLVirtualTable(pvTab^.pInstance).Drop then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[],'vt_Destroy');
    {$endif}
    result := SQLITE_ERROR;
  end;
  vt_Disconnect(pVTab); // release memory
end;

function vt_BestIndex(var pVTab: TSQLite3VTab; var pInfo: TSQLite3IndexInfo): Integer;
................................................................................
    i, n: Integer;
begin
  result := SQLITE_ERROR;
  Table := TSQLVirtualTable(pvTab.pInstance);
  if (cardinal(pInfo.nOrderBy)>MAX_SQLFIELDS) or
     (cardinal(pInfo.nConstraint)>MAX_SQLFIELDS) then begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[pInfo.nOrderBy,pInfo.nConstraint],'nOrderBy=% nConstraint=%');
    {$endif}
    exit; // avoid buffer overflow
  end;
  Prepared := sqlite3.malloc(sizeof(TSQLVirtualTablePrepared));
  try
    // encode the incoming parameters into Prepared^ record
    fillchar(Prepared^,sizeof(Prepared^),0);
................................................................................
  if Prepared^.WhereCount<>argc then
    exit; // invalid prepared array
  for i := 0 to argc-1 do
    SQlite3ValueToSQLVar(argv[i],Prepared^.Where[i].Value);
  if TSQLVirtualTableCursor(pVtabCursor.pInstance).Search(Prepared^) then
    result := SQLITE_OK else
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[],'vt_Filter');
    {$endif}
end;

function vt_Open(var pVTab: TSQLite3VTab; var ppCursor: PSQLite3VTabCursor): Integer;
  {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
var Table: TSQLVirtualTable;
begin
................................................................................
  if ppCursor=nil then begin
    result := SQLITE_NOMEM;
    exit;
  end;
  Table := TSQLVirtualTable(pvTab.pInstance);
  if (Table=nil) or (Table.Module=nil) or (Table.Module.CursorClass=nil) then begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[],'vt_Open');
    {$endif}
    sqlite3.free_(ppCursor);
    result := SQLITE_ERROR;
    exit;
  end;
  ppCursor.pInstance := Table.Module.CursorClass.Create(Table);
  result := SQLITE_OK;
................................................................................
var Res: TSQLVar;
begin
  Res.VType := ftUnknown;
  if (N>=0) and TSQLVirtualTableCursor(pVtabCursor.pInstance).Column(N,Res) and
     SQLVarToSQlite3Context(Res,sContext) then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[N,ord(Res.VType)],'vt_Column(%) Res=%');
    {$endif}
    result := SQLITE_ERROR;
  end;
end;

function vt_Rowid(var pVtabCursor: TSQLite3VTabCursor; var pRowid: Int64): Integer;
  {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
................................................................................
    case Res.VType of
    ftInt64:    pRowID := Res.VInt64;
    ftDouble:   pRowID := trunc(Res.VDouble);
    ftCurrency: pRowID := trunc(Res.VCurrency);
    ftUTF8:     pRowID := GetInt64(Res.VText);
    else begin
      {$ifdef WITHLOG}
      SynSQLite3Log.DebuggerNotify(sllWarning,[ord(Res.VType)],'vt_Rowid Res=%');
      {$endif}
      exit;
    end;
    end;
    result := SQLITE_OK;
  end else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[],'vt_Rowid Column');
    {$endif}
  end;
end;

function vt_Update(var pVTab: TSQLite3VTab;
  nArg: Integer; var ppArg: TSQLite3ValueArray;
  var pRowid: Int64): Integer; {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
................................................................................
    if RowID0=0 then
      OK := Table.Insert(RowID1,Values,pRowid) else
      OK := Table.Update(RowID0,RowID1,Values);
  end;
  if OK then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[pRowID],'vt_Update(%)');
    {$endif}
  end;
end;

function InternalTrans(pVTab: TSQLite3VTab; aState: TSQLVirtualTableTransaction;
  aSavePoint: integer): integer;
begin
  if TSQLVirtualTable(pvTab.pInstance).Transaction(aState,aSavePoint) then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[GetEnumName(TypeInfo(TSQLVirtualTableTransaction),
      ord(aState))^,aSavePoint],'Transaction(%,%)');
    {$endif}
    result := SQLITE_ERROR;
  end;
end;

function vt_Begin(var pVTab: TSQLite3VTab): Integer; {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
begin
................................................................................

function vt_Rename(var pVTab: TSQLite3VTab; const zNew: PAnsiChar): Integer;
  {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
begin
  if TSQLVirtualTable(pvTab.pInstance).Rename(RawUTF8(zNew)) then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,[zNew],'vt_Rename(%)');
    {$endif}
    result := SQLITE_ERROR;
  end;
end;

procedure sqlite3InternalFreeModule(p: pointer); {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
begin






>











|
>
>
>
>
>
>
>







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







 







|







|







 







|










|
|







 







|







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
...
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
....
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
....
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
....
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
....
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
....
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
....
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
....
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
....
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
....
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
....
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
....
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
....
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
procedure TSQLRestServerDB.GetAndPrepareStatement(const SQL: RawUTF8;
  ForceCacheStatement: boolean);
var i, maxParam,sqlite3param: integer;
    Types: TSQLParamTypeDynArray;
    Nulls: TSQLFieldBits;
    Values: TRawUTF8DynArray;
    wasPrepared: boolean;
begin
  fStatementTimer.Start;
  fStatementSQL := SQL;
  fStatementGenericSQL := ExtractInlineParameters(SQL,Types,Values,maxParam,Nulls);
  if (maxParam=0) and not ForceCacheStatement then begin
    // SQL code with no valid :(...): internal parameters
    fStatementGenericSQL := '';
    fStaticStatement.Prepare(DB.DB,SQL);
    fStatement := @fStaticStatement;
    exit;
  end;
  fStatement := fStatementCache.Prepare(fStatementGenericSQL,@wasPrepared);
  if wasPrepared then begin
    {$ifdef WITHLOG}
    fLogClass.Add.Log(sllDB,'prepared % % %',
      [fStatementTimer.Stop,DB.FileNameWithoutPath,fStatementGenericSQL],self);
    {$endif}
    fStatementTimer.Start;
  end;
  // bind parameters
  sqlite3param := sqlite3.bind_parameter_count(fStatement^.Request);
  if sqlite3param<>maxParam then
    raise EORMException.CreateUTF8(
      '%.GetAndPrepareStatement(%) recognized % params, and % for SQLite3',
      [self,fStatementGenericSQL,maxParam,sqlite3param]);
  for i := 0 to maxParam-1 do
................................................................................
  if fStatement=@fStaticStatement then
    fStaticStatement.Close;
  fStatement := nil;
  fStatementSQL := '';
  fStatementGenericSQL := '';
  if E<>nil then
    fStatementLastException := FormatUTF8('% %',[E,ObjectToJSON(E)]);
end;

procedure TSQLRestServerDB.FlushStatementCache;
begin
  DB.Lock;
  try
    fStatementCache.ReleaseAllDBStatements;
  finally
................................................................................
      if Res.VText=nil then
       sqlite3.result_text(Context,@NULCHAR,0,SQLITE_STATIC) else
       sqlite3.result_text(Context,Res.VText,-1,SQLITE_TRANSIENT_VIRTUALTABLE);
    ftBlob:
      sqlite3.result_blob(Context,Res.VBlob,Res.VBlobLen,SQLITE_TRANSIENT_VIRTUALTABLE);
    else begin
      {$ifdef WITHLOG}
      SynSQLite3Log.DebuggerNotify(sllWarning,'SQLVarToSQlite3Context(%)',[ord(Res.VType)]);
      {$endif}
      result := false; // not handled type
      exit;
    end;
  end;
  result := true;
end;
................................................................................
  SQLITE_BLOB: begin
    Res.VType := ftBlob;
    Res.VBlobLen := sqlite3.value_bytes(Value);
    Res.VBlob := sqlite3.value_blob(Value);
  end;
  else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'SQlite3ValueToSQLVar(%)',[ValueType]);
    {$endif}
    Res.VType := ftUnknown;
  end;
  end;
end;

function TSQLVirtualTableModuleSQLite3.FileName(const aTableName: RawUTF8): TFileName;
................................................................................
    ModuleName: RawUTF8;
begin
  if Module<>nil then
    ModuleName := Module.ModuleName;
  if (Module=nil) or (Module.DB.DB<>DB) or
     (StrIComp(pointer(ModuleName),argv[0])<>0) then begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Create(%<>%)',[argv[0],ModuleName]);
    {$endif}
    result := SQLITE_ERROR;
    exit;
  end;
  ppVTab := sqlite3.malloc(sizeof(TSQLite3VTab));
  if ppVTab=nil then begin
    result := SQLITE_NOMEM;
................................................................................
      exit;
    end;
  end;
  Structure := Table.Structure;
  result := sqlite3.declare_vtab(DB,pointer(Structure));
  if result<>SQLITE_OK then begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Create(%) declare_vtab(%)',[ModuleName,Structure]);
    {$endif}
    Table.Free;
    sqlite3.free_(ppVTab);
    result := SQLITE_ERROR;
  end else
    ppVTab^.pInstance := Table;
end;
................................................................................
end;

function vt_Destroy(pVTab: PSQLite3VTab): Integer; {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
begin
  if TSQLVirtualTable(pvTab^.pInstance).Drop then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Destroy',[]);
    {$endif}
    result := SQLITE_ERROR;
  end;
  vt_Disconnect(pVTab); // release memory
end;

function vt_BestIndex(var pVTab: TSQLite3VTab; var pInfo: TSQLite3IndexInfo): Integer;
................................................................................
    i, n: Integer;
begin
  result := SQLITE_ERROR;
  Table := TSQLVirtualTable(pvTab.pInstance);
  if (cardinal(pInfo.nOrderBy)>MAX_SQLFIELDS) or
     (cardinal(pInfo.nConstraint)>MAX_SQLFIELDS) then begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'nOrderBy=% nConstraint=%',[pInfo.nOrderBy,pInfo.nConstraint]);
    {$endif}
    exit; // avoid buffer overflow
  end;
  Prepared := sqlite3.malloc(sizeof(TSQLVirtualTablePrepared));
  try
    // encode the incoming parameters into Prepared^ record
    fillchar(Prepared^,sizeof(Prepared^),0);
................................................................................
  if Prepared^.WhereCount<>argc then
    exit; // invalid prepared array
  for i := 0 to argc-1 do
    SQlite3ValueToSQLVar(argv[i],Prepared^.Where[i].Value);
  if TSQLVirtualTableCursor(pVtabCursor.pInstance).Search(Prepared^) then
    result := SQLITE_OK else
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Filter',[]);
    {$endif}
end;

function vt_Open(var pVTab: TSQLite3VTab; var ppCursor: PSQLite3VTabCursor): Integer;
  {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
var Table: TSQLVirtualTable;
begin
................................................................................
  if ppCursor=nil then begin
    result := SQLITE_NOMEM;
    exit;
  end;
  Table := TSQLVirtualTable(pvTab.pInstance);
  if (Table=nil) or (Table.Module=nil) or (Table.Module.CursorClass=nil) then begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Open',[]);
    {$endif}
    sqlite3.free_(ppCursor);
    result := SQLITE_ERROR;
    exit;
  end;
  ppCursor.pInstance := Table.Module.CursorClass.Create(Table);
  result := SQLITE_OK;
................................................................................
var Res: TSQLVar;
begin
  Res.VType := ftUnknown;
  if (N>=0) and TSQLVirtualTableCursor(pVtabCursor.pInstance).Column(N,Res) and
     SQLVarToSQlite3Context(Res,sContext) then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Column(%) Res=%',[N,ord(Res.VType)]);
    {$endif}
    result := SQLITE_ERROR;
  end;
end;

function vt_Rowid(var pVtabCursor: TSQLite3VTabCursor; var pRowid: Int64): Integer;
  {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
................................................................................
    case Res.VType of
    ftInt64:    pRowID := Res.VInt64;
    ftDouble:   pRowID := trunc(Res.VDouble);
    ftCurrency: pRowID := trunc(Res.VCurrency);
    ftUTF8:     pRowID := GetInt64(Res.VText);
    else begin
      {$ifdef WITHLOG}
      SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Rowid Res=%',[ord(Res.VType)]);
      {$endif}
      exit;
    end;
    end;
    result := SQLITE_OK;
  end else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Rowid Column',[]);
    {$endif}
  end;
end;

function vt_Update(var pVTab: TSQLite3VTab;
  nArg: Integer; var ppArg: TSQLite3ValueArray;
  var pRowid: Int64): Integer; {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
................................................................................
    if RowID0=0 then
      OK := Table.Insert(RowID1,Values,pRowid) else
      OK := Table.Update(RowID0,RowID1,Values);
  end;
  if OK then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Update(%)',[pRowID]);
    {$endif}
  end;
end;

function InternalTrans(pVTab: TSQLite3VTab; aState: TSQLVirtualTableTransaction;
  aSavePoint: integer): integer;
begin
  if TSQLVirtualTable(pvTab.pInstance).Transaction(aState,aSavePoint) then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'Transaction(%,%)',
      [GetEnumName(TypeInfo(TSQLVirtualTableTransaction),ord(aState))^,aSavePoint]);
    {$endif}
    result := SQLITE_ERROR;
  end;
end;

function vt_Begin(var pVTab: TSQLite3VTab): Integer; {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
begin
................................................................................

function vt_Rename(var pVTab: TSQLite3VTab; const zNew: PAnsiChar): Integer;
  {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
begin
  if TSQLVirtualTable(pvTab.pInstance).Rename(RawUTF8(zNew)) then
    result := SQLITE_OK else begin
    {$ifdef WITHLOG}
    SynSQLite3Log.DebuggerNotify(sllWarning,'vt_Rename(%)',[zNew]);
    {$endif}
    result := SQLITE_ERROR;
  end;
end;

procedure sqlite3InternalFreeModule(p: pointer); {$ifndef SQLITE3_FASTCALL}cdecl;{$endif}
begin

Changes to SQLite3/mORMotSelfTests.pas.

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
  AllocConsole;
  {$endif}
  TSynLogTestLog := TSQLLog; // share the same log file with whole mORMot
  TSQLLog.Family.Level := LOG_STACKTRACE; // log errors by default
  if false then // "if not false then" will create around 550 MB of log file
  with TSQLLog.Family do begin
    Level := LOG_VERBOSE;
    //DestinationPath := ExtractFilePath(paramstr(0))+'logs'; folder should exist
    PerThreadLog := ptIdentifiedInOnFile;
    //HighResolutionTimeStamp := true;
    //RotateFileCount := 5; RotateFileSizeKB := 20*1024; // rotate by 20 MB logs
  end
  else
    TSQLLog.Family.Level := []; // NO log by default (ignore expected ERROR 400)
  // testing is performed by some dedicated classes defined in the above units






|







188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
  AllocConsole;
  {$endif}
  TSynLogTestLog := TSQLLog; // share the same log file with whole mORMot
  TSQLLog.Family.Level := LOG_STACKTRACE; // log errors by default
  if false then // "if not false then" will create around 550 MB of log file
  with TSQLLog.Family do begin
    Level := LOG_VERBOSE;
    //DestinationPath := ExeVersion.ProgramFilePath+'logs'; folder should exist
    PerThreadLog := ptIdentifiedInOnFile;
    //HighResolutionTimeStamp := true;
    //RotateFileCount := 5; RotateFileSizeKB := 20*1024; // rotate by 20 MB logs
  end
  else
    TSQLLog.Family.Level := []; // NO log by default (ignore expected ERROR 400)
  // testing is performed by some dedicated classes defined in the above units

Changes to SQLite3/mORMotService.pas.

652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
...
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
  fStartType   := SERVICE_AUTO_START;
  fStatusRec.dwServiceType := fServiceType;
  fStatusRec.dwCurrentState := SERVICE_STOPPED;
  fStatusRec.dwControlsAccepted := 31;
  fStatusRec.dwWin32ExitCode := NO_ERROR;
  {$ifndef NOMORMOTKERNEL}
  SQLite3Log.Add.Log(sllInfo,'% (%) running as "%"',
    [ServiceName,aDisplayName,ParamStr(0)],self);
  {$endif}
end;

procedure TService.CtrlHandle(Code: DWORD);
begin
  DoCtrlHandle(Code);
end;
................................................................................
    Free;
  end;
end;

function TService.Install(const Params: string): boolean;
var schService: SC_HANDLE;
    schSCManager: SC_HANDLE;
    ServicePath: String;
begin
  result := false;
  if installed then
    exit;
  ServicePath := paramstr(0);
  if Params<>'' then
    ServicePath := ServicePath+' '+Params;
  schSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if (schSCManager>0) then begin
     schService := CreateService(schSCManager,
       pointer(fSName), pointer(fDName), SERVICE_ALL_ACCESS,
       fServiceType, fStartType, SERVICE_ERROR_NORMAL,






|







 







|




|







652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
...
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
  fStartType   := SERVICE_AUTO_START;
  fStatusRec.dwServiceType := fServiceType;
  fStatusRec.dwCurrentState := SERVICE_STOPPED;
  fStatusRec.dwControlsAccepted := 31;
  fStatusRec.dwWin32ExitCode := NO_ERROR;
  {$ifndef NOMORMOTKERNEL}
  SQLite3Log.Add.Log(sllInfo,'% (%) running as "%"',
    [ServiceName,aDisplayName,ExeVersion.ProgramFullSpec],self);
  {$endif}
end;

procedure TService.CtrlHandle(Code: DWORD);
begin
  DoCtrlHandle(Code);
end;
................................................................................
    Free;
  end;
end;

function TService.Install(const Params: string): boolean;
var schService: SC_HANDLE;
    schSCManager: SC_HANDLE;
    ServicePath: TFileName;
begin
  result := false;
  if installed then
    exit;
  ServicePath := ExeVersion.ProgramFileName;
  if Params<>'' then
    ServicePath := ServicePath+' '+Params;
  schSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
  if (schSCManager>0) then begin
     schService := CreateService(schSCManager,
       pointer(fSName), pointer(fDName), SERVICE_ALL_ACCESS,
       fServiceType, fStartType, SERVICE_ERROR_NORMAL,

Changes to SQLite3/mORMotWrappers.pas.

844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
procedure ComputeSearchPath(const Path: array of TFileName;
  out SearchPath: TFileNameDynArray);
var i: integer;
begin
  if length(Path)=0 then begin
    SetLength(SearchPath,1);
    SearchPath[0] := ExtractFilePath(paramstr(0)); // use .exe path
  end else begin
    SetLength(SearchPath,length(Path));
    for i := 0 to high(Path) do
      SearchPath[i] := Path[i];
  end;
end;







|







844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
procedure ComputeSearchPath(const Path: array of TFileName;
  out SearchPath: TFileNameDynArray);
var i: integer;
begin
  if length(Path)=0 then begin
    SetLength(SearchPath,1);
    SearchPath[0] := ExeVersion.ProgramFilePath; // use .exe path
  end else begin
    SetLength(SearchPath,length(Path));
    for i := 0 to high(Path) do
      SearchPath[i] := Path[i];
  end;
end;

Changes to SQLite3/mORMoti18n.pas.

1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
....
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
....
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
end;

procedure SetCurrentLanguage(const value: RawUTF8); overload;
begin
  SetCurrentLanguage(LanguageAbrToIndex(value));
end;

function ProgramName: AnsiString;
var i: integer;
begin
  result := AnsiString(ExtractFileName(paramstr(0)));
  i := Pos(RawUTF8('.'),RawUTF8(result));
  if i>0 then
    Setlength(result,i-1);
end;

{$ifdef USEFORMCREATEHOOK}

function i18nAddLanguageItems(MsgPath: TFileName; List: TStrings): integer;
var SR: TSearchRec;
    lng, index: TLanguages;
    Exists: set of TLanguages;
begin
  if MsgPath='' then
    MsgPath := ExtractFilePath(paramstr(0));
  result := -1; // no language selection if no language available
  fillchar(Exists,sizeof(Exists),0);
  include(Exists,lngEnglish); // English is always present (default built in EXE)
  if FindFirst(MsgPath+'*.msg', faAnyFile, SR)<>0 then
    exit;
  repeat
    lng := LanguageAbrToIndex(
................................................................................
  FreeAndNil(Messages);
  inherited;
end;

class function TLanguageFile.FileName(aLanguageLocale: TLanguages): TFileName;
begin
  if aLanguageLocale<>LANGUAGE_NONE then
    result :=  ExtractFilePath(paramstr(0))+
      Ansi7ToString(LanguageAbr[aLanguageLocale])+'.msg' else
    result := '';
end;

{$ifndef USEFORMCREATEHOOK}
procedure TLanguageFile.FormTranslate(Forms: array of TCustomForm);
var f: integer;
................................................................................
  end;
                       
begin
  // all code below use *A() Win32 API -> only english=Ansi text is expected here
  CB_Enum.Init(TypeInfo(TWinAnsiDynArray),CB_EnumStrings,nil,nil,Hash32Str,@CB_EnumStringsCount);
  ClassList := TList.Create;
  try
    assign(F,ChangeFileExt(paramstr(0),'.messages'));
    SetLength(buf,65536);
    settextbuf(F,buf[1],length(buf));
    Rewrite(F);
    // add all resourcestring values
    EnumResourceNamesA(HInstance,PAnsiChar(RT_STRING),@CB_EnumStringProc,0);
    // add all enumerates captions
    for i := 0 to high(EnumTypeInfo) do






<
<
<
<
<
<
<
<
<








|







 







|







 







|







1312
1313
1314
1315
1316
1317
1318









1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
....
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
....
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
end;

procedure SetCurrentLanguage(const value: RawUTF8); overload;
begin
  SetCurrentLanguage(LanguageAbrToIndex(value));
end;










{$ifdef USEFORMCREATEHOOK}

function i18nAddLanguageItems(MsgPath: TFileName; List: TStrings): integer;
var SR: TSearchRec;
    lng, index: TLanguages;
    Exists: set of TLanguages;
begin
  if MsgPath='' then
    MsgPath := ExeVersion.ProgramFilePath;
  result := -1; // no language selection if no language available
  fillchar(Exists,sizeof(Exists),0);
  include(Exists,lngEnglish); // English is always present (default built in EXE)
  if FindFirst(MsgPath+'*.msg', faAnyFile, SR)<>0 then
    exit;
  repeat
    lng := LanguageAbrToIndex(
................................................................................
  FreeAndNil(Messages);
  inherited;
end;

class function TLanguageFile.FileName(aLanguageLocale: TLanguages): TFileName;
begin
  if aLanguageLocale<>LANGUAGE_NONE then
    result :=  ExeVersion.ProgramFilePath+
      Ansi7ToString(LanguageAbr[aLanguageLocale])+'.msg' else
    result := '';
end;

{$ifndef USEFORMCREATEHOOK}
procedure TLanguageFile.FormTranslate(Forms: array of TCustomForm);
var f: integer;
................................................................................
  end;
                       
begin
  // all code below use *A() Win32 API -> only english=Ansi text is expected here
  CB_Enum.Init(TypeInfo(TWinAnsiDynArray),CB_EnumStrings,nil,nil,Hash32Str,@CB_EnumStringsCount);
  ClassList := TList.Create;
  try
    assign(F,ChangeFileExt(ExeVersion.ProgramFileName,'.messages'));
    SetLength(buf,65536);
    settextbuf(F,buf[1],length(buf));
    Rewrite(F);
    // add all resourcestring values
    EnumResourceNamesA(HInstance,PAnsiChar(RT_STRING),@CB_EnumStringProc,0);
    // add all enumerates captions
    for i := 0 to high(EnumTypeInfo) do

Changes to SynCommons.pas.

8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578



8579
8580
8581
8582
8583
8584
8585
....
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602

8603

8604
8605
8606
8607


8608
8609
8610
8611
8612
8613
8614
....
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635


8636
8637
8638
8639
8640
8641
8642
....
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
....
8746
8747
8748
8749
8750
8751
8752



































8753
8754
8755
8756
8757
8758
8759
....
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
.....
13734
13735
13736
13737
13738
13739
13740











13741
13742
13743
13744
13745
13746
13747
.....
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
.....
24328
24329
24330
24331
24332
24333
24334
24335

24336








































































24337
24338
24339


24340

24341





24342

24343





24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359

24360
24361
24362
24363
24364
24365




24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405

24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
.....
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
.....
43199
43200
43201
43202
43203
43204
43205

43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
  // - defined as unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
  // in @http://tools.ietf.org/html/rfc3986#section-2.3
  IsURIUnreserved: set of byte =
    [ord('a')..ord('z'),ord('A')..ord('Z'),ord('0')..ord('9'),
     ord('-'),ord('.'),ord('_'),ord('~')];


{$ifdef MSWINDOWS}

{$M+} // to have existing RTTI for published properties
type
  /// used to retrieve version information from any EXE



  TFileVersion = class
  protected
    fDetailed: string;
    fBuildDateTime: TDateTime;
  public
    /// executable major version number
    Major: Integer;
................................................................................
    /// executable minor version number
    Minor: Integer;
    /// executable release version number
    Release: Integer;
    /// executable release build number
    Build: Integer;
    /// build year of this exe file
    BuildYear: integer;
    /// version info of the exe file as '3.1'
    // - return "string" type, i.e. UnicodeString for Delphi 2009+
    Main: string;
    /// retrieve application version from exe file name
    // - DefaultVersion is used if no information Version was included into
    // the executable resources (on compilation time)
    // - to retrieve version information from current executable, just call
    // ExeVersionRetrieve function, then use ExeVersion global variable
    constructor Create(const FileName: TFileName; DefaultVersion: integer);

    /// retrieve the version as a 32 bits integer with Major.Minor.Release

    function Version32: integer;
  published
    /// version info of the exe file as '3.1.0.123'
    // - return "string" type, i.e. UnicodeString for Delphi 2009+


    property Detailed: string read fDetailed write fDetailed;
    /// build date and time of this exe file
    property BuildDateTime: TDateTime read fBuildDateTime write fBuildDateTime;
  end;
{$M-}


................................................................................
  SecsPerMin    = 60;
  MSecsPerSec   = 1000;
  MinsPerDay    = HoursPerDay * MinsPerHour;
  SecsPerDay    = MinsPerDay * SecsPerMin;
  MSecsPerDay   = SecsPerDay * MSecsPerSec;
  UnixDateDelta = 25569;

{/ GetFileVersion returns the most significant 32 bits of a file's binary
  version number
  - Typically, this includes the major and minor version placed
  together in one 32-bit integer
  - It generally does not include the release or build numbers
  - It returns Cardinal(-1) if it failed }
function GetFileVersion(const FileName: TFileName): cardinal;
{$endif}



type
  /// the recognized Windows versions
  TWindowsVersion = (
    wUnknown, w2000, wXP, wXP_64, wServer2003, wServer2003_R2,
    wVista, wVista_64, wServer2008, wServer2008_64,
    wServer2008_R2, wServer2008_R2_64, wSeven, wSeven_64,
................................................................................
  // more optimistic/realistic value ($100000 instead of default $10000)
  SystemInfo: TSystemInfo;
  /// the current Operating System information, as retrieved for the current process
  OSVersionInfo: TOSVersionInfoEx;
  /// the current Operating System version, as retrieved for the current process
  OSVersion: TWindowsVersion;

  /// global information about the current executable and computer
  // - call ExeVersionRetrieve before using it (it is done by mORMot.pas unit)
  ExeVersion: record
    /// the main executable name, without any path nor extension
    ProgramName: RawUTF8;
    /// the main executable details, as used e.g. by TSynLog
    // - e.g. 'C:\Dev\lib\SQLite3\exe\TestSQL3.exe 0.0.0.0 (2011-03-29 11:09:06)'
    ProgramFullSpec: RawUTF8;
    /// the main executable file name (including full path)
    // - same as paramstr(0)
    ProgramFileName: TFileName;
    /// the main executable full path (excluding .exe file name)
    // - same as ExtractFilePath(paramstr(0))
    ProgramFilePath: TFileName;
    /// the full path of the running executable or library
    // - for an executable, same as paramstr(0) 
    // - for a library, will contain the whole .dll file name 
    InstanceFileName: TFileName;
    /// the current executable version
    Version: TFileVersion;
    /// the current computer host name
    Host: RawUTF8;
    /// the current computer user name
    User: RawUTF8;
  end;

/// initialize ExeVersion global variable, if not already done
procedure ExeVersionRetrieve(DefaultVersion: integer=0);

{/ this function can be used to create a GDI compatible window, able to
  receive Windows Messages for fast local communication
  - will return 0 on failure (window name already existing e.g.), or
    the created HWND handle on success
  - it will call the supplied message handler defined for a given Windows Message:
    for instance, define such a method in any object definition:
  !  procedure WMCopyData(var Msg : TWMCopyData); message WM_COPYDATA; }
................................................................................
/// compatibility function, to be implemented according to the running OS
// - expect more or less the same result as the homonymous Win32 API function
// - will call the corresponding function in SynKylix.pas or SynFPCLinux.pas 
function GetTickCount64: Int64;

{$endif MSWINDOWS}




































/// self-modifying code - change some memory buffer in the code segment
// - if Backup is not nil, it should point to a Size array of bytes, ready
// to contain the overridden code buffer, for further hook disabling
procedure PatchCode(Old,New: pointer; Size: integer; Backup: pointer=nil;
  LeaveUnprotected: boolean=false);

/// self-modifying code - change one PtrUInt in the code segment
................................................................................

var
  /// a global "Garbage collector", for some classes instances which must
  // live during whole main executable process
  // - used to avoid any memory leak with e.g. 'class var RecordProps', i.e.
  // some singleton or static objects
  // - to be used, e.g. as:
  // !  Version := TFileVersion.Create(InstanceFileName,DefaultVersion);
  // !  GarbageCollector.Add(Version);
  GarbageCollector: TObjectList;

  /// set to TRUE when the global "Garbage collector" are beeing freed
  GarbageCollectorFreeing: boolean;

/// a global "Garbage collector" for some TObject global variables which must
................................................................................
  end else
    P := StrUInt64(P,val);
  result := P;
end;


// some minimal RTTI const and types












{$ifdef FPC}

type
  /// available type families for Free Pascal RTTI values
  // - values differs from Delphi, and are taken from FPC typinfo.pp unit
  // - here below, we defined tkLString instead of FPC tkAString to match
................................................................................
    jnz @1
    xor eax,eax
@z:
end;
{$endif}

function StringReplaceChars(const Source: RawUTF8; OldChar, NewChar: AnsiChar): RawUTF8;
var c: AnsiChar;
    i: integer;
begin
  result := '';
  if Source='' then
    exit;
  SetLength(result,length(Source));
  i := 0;
  repeat
    c := PUTF8Char(pointer(Source))[i];
    if c=#0 then
      exit;
    if c=OldChar then
      c := NewChar;
    PUTF8Char(pointer(result))[i] := c;
    inc(i);
  until false;
end;

function PosI(uppersubstr: PUTF8Char; const str: RawUTF8): Integer;
var C: AnsiChar;
begin
  if uppersubstr<>nil then begin
    C := uppersubstr^;
................................................................................
    aWindow := 0;
    aWindowName := '';
    result := true;
  end else
    result := false;
end;

procedure ExeVersionRetrieve(DefaultVersion: integer);

const EXE_FMT: PUTF8Char = '% % (%)';








































































var Tmp: array[byte] of AnsiChar;
    TmpSize: cardinal;
    i: integer;


begin

  with ExeVersion do





  if Version=nil then begin

    ProgramFileName := paramstr(0);





    ProgramFilePath := ExtractFilePath(ProgramFileName);
    if IsLibrary then
      InstanceFileName := GetModuleName(HInstance) else
      InstanceFileName := ProgramFileName;
    Version := TFileVersion.Create(InstanceFileName,DefaultVersion);
    GarbageCollector.Add(Version);
    ProgramFullSpec := FormatUTF8(EXE_FMT,
      [ProgramFileName,Version.Detailed,DateTimeToIso8601(Version.BuildDateTime,True,' ')]);
    ProgramName := StringToUTF8(ExtractFileName(ProgramFileName));
    i := length(ProgramName);
    while i>0 do
      if ProgramName[i]='.' then begin
        SetLength(ProgramName,i-1);
        break;
      end else
      dec(i);

    TmpSize := sizeof(Tmp);
    GetComputerNameA(Tmp,TmpSize);
    Host := Tmp;
    TmpSize := sizeof(Tmp);
    GetUserNameA(Tmp,TmpSize);
    User := Tmp;




  end;
end;


{ TFileVersion }

constructor TFileVersion.Create(const FileName: TFileName;
  DefaultVersion: integer);
var Size, Size2: DWord;
    Pt: Pointer;
    Info: ^TVSFixedFileInfo;
    FileTime: TFILETIME;
    SystemTime: TSYSTEMTIME;
    tmp: TFileName;
begin
  Major := DefaultVersion;
  if FileName='' then
    exit;
  // GetFileVersionInfo modifies the filename parameter data while parsing.
  // Copy the string const into a local variable to create a writeable copy.
  SetString(tmp,PChar(FileName),length(FileName));
  Size := GetFileVersionInfoSize(pointer(tmp), Size2);
  if Size>0 then begin
    GetMem(Pt, Size);
    try
      GetFileVersionInfo(pointer(FileName), 0, Size, Pt);
      VerQueryValue(Pt, '\', pointer(Info), Size2);
      with Info^ do begin
        Major := dwFileVersionMS shr 16;
        Minor := word(dwFileVersionMS);
        Release := dwFileVersionLS shr 16;
        Build := word(dwFileVersionLS);
        BuildYear := 2010;
        if (dwFileDateLS<>0) and (dwFileDateMS<>0) then begin
          FileTime.dwLowDateTime:= dwFileDateLS; // built date from version info
          FileTime.dwHighDateTime:= dwFileDateMS;
          FileTimeToSystemTime(FileTime, SystemTime);
          fBuildDateTime := EncodeDate(
            SystemTime.wYear,SystemTime.wMonth,SystemTime.wDay);
          BuildYear := SystemTime.wYear;

        end;
      end;
    finally
      Freemem(Pt);
    end;
  end;
  Main := IntToString(Major)+'.'+IntToString(Minor);
  fDetailed := Main+ '.'+IntToString(Release)+'.'+IntToString(Build);
  if fBuildDateTime=0 then // get build date from file age
    fBuildDateTime := FileAgeToDateTime(FileName);
end;

function TFileVersion.Version32: integer;
begin
  result := Major shl 16+Minor shl 8+Release;
end;

{$else}

const
  _SC_PAGE_SIZE = $1000;

{$endif MSWINDOWS}



procedure PatchCode(Old,New: pointer; Size: integer; Backup: pointer=nil;
  LeaveUnprotected: boolean=false);
{$ifdef MSWINDOWS}
var RestoreProtection, Ignore: DWORD;
    i: integer;
................................................................................
  if VKind=dvArray then
    for result := 0 to VCount-1 do
      if VValue[result]=aValue then // rely on Variants.pas comparison
        exit;
  result := -1;
end;

procedure Exchg(P1,P2: PAnsiChar; count: integer);
var c: AnsiChar;
begin
  while count>0 do begin
    dec(count);
    c := P1[count];
    P1[count] := P2[count];
    P2[count] := c;
  end;
end;

procedure QuickSortDocVariant(names: PPointerArray; values: PVariantArray;
  L, R: PtrInt; Compare: TUTF8Compare);
var I, J, P: PtrInt;
    pivot, Tmp: pointer;
begin
  if L<R then
  repeat
................................................................................
  {$endif USEPACKAGES}
  {$endif CPUARM}
  {$endif FPC}
  InitSynCommonsConversionTables;
  {$ifdef MSWINDOWS}
  RetrieveSystemInfo;
  {$endif MSWINDOWS}

  // some type definition assertions
  Assert(SizeOf(TSynTableFieldType)=1); // as expected by TSynTableFieldProperties
  Assert(SizeOf(TSynTableFieldOptions)=1);
  {$ifndef NOVARIANTS}
  Assert(SizeOf(TSynTableData)=sizeof(TVarData));
  Assert(SizeOf(TDocVariantData)=sizeof(TVarData));
  {$endif NOVARIANTS}

finalization
  GarbageCollectorFree;
  if GlobalCriticalSectionInitialized then
    DeleteCriticalSection(GlobalCriticalSection);
end.






<
<



>
>
>







 







|




|

|
|
|
>

>




>
>







 







|
|
|
|
|
|


>
>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







>
>
>
>
>
>
>
>
>
>
>







 







|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<







 







<
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

<
>
>

>

>
>
>
>
>

>

>
>
>
>
>




|

|









>






>
>
>
>
|
|
<
<
<
<
<
|
|
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<
<







 







>













8567
8568
8569
8570
8571
8572
8573


8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
....
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
....
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
....
8680
8681
8682
8683
8684
8685
8686





























8687
8688
8689
8690
8691
8692
8693
....
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
....
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
.....
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
.....
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218



15219
15220
15221
15222
15223
15224
15225
.....
24349
24350
24351
24352
24353
24354
24355

24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431

24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478





24479
24480







24481























24482
24483
24484






















24485
24486
24487
24488
24489
24490
24491
.....
29553
29554
29555
29556
29557
29558
29559











29560
29561
29562
29563
29564
29565
29566
.....
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
  // - defined as unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
  // in @http://tools.ietf.org/html/rfc3986#section-2.3
  IsURIUnreserved: set of byte =
    [ord('a')..ord('z'),ord('A')..ord('Z'),ord('0')..ord('9'),
     ord('-'),ord('.'),ord('_'),ord('~')];




{$M+} // to have existing RTTI for published properties
type
  /// used to retrieve version information from any EXE
  // - under Linux, all version numbers are set to 0 by default
  // - you should not have to use this class directly, but via the
  // ExeVersion global variable
  TFileVersion = class
  protected
    fDetailed: string;
    fBuildDateTime: TDateTime;
  public
    /// executable major version number
    Major: Integer;
................................................................................
    /// executable minor version number
    Minor: Integer;
    /// executable release version number
    Release: Integer;
    /// executable release build number
    Build: Integer;
    /// build year of this exe file
    BuildYear: word;
    /// version info of the exe file as '3.1'
    // - return "string" type, i.e. UnicodeString for Delphi 2009+
    Main: string;
    /// retrieve application version from exe file name
    // - DefaultVersion32 is used if no information Version was included into
    // the executable resources (on compilation time)
    // - you should not have to use this constructor, but rather access the
    // ExeVersion global variable
    constructor Create(const aFileName: TFileName;
      aMajor,aMinor,aRelease: integer);
    /// retrieve the version as a 32 bits integer with Major.Minor.Release
    // - following Major shl 16+Minor shl 8+Release bit pattern
    function Version32: integer;
  published
    /// version info of the exe file as '3.1.0.123'
    // - return "string" type, i.e. UnicodeString for Delphi 2009+
    // - under Linux, always return '0.0.0.0' if no custom version number
    // has been defined
    property Detailed: string read fDetailed write fDetailed;
    /// build date and time of this exe file
    property BuildDateTime: TDateTime read fBuildDateTime write fBuildDateTime;
  end;
{$M-}


................................................................................
  SecsPerMin    = 60;
  MSecsPerSec   = 1000;
  MinsPerDay    = HoursPerDay * MinsPerHour;
  SecsPerDay    = MinsPerDay * SecsPerMin;
  MSecsPerDay   = SecsPerDay * MSecsPerSec;
  UnixDateDelta = 25569;

/// GetFileVersion returns the most significant 32 bits of a file's binary
// version number
// - typically, this includes the major and minor version placed
// together in one 32-bit integer
// - generally does not include the release or build numbers
// - returns Cardinal(-1) in case of failure 
function GetFileVersion(const FileName: TFileName): cardinal;
{$endif}

{$ifdef MSWINDOWS}

type
  /// the recognized Windows versions
  TWindowsVersion = (
    wUnknown, w2000, wXP, wXP_64, wServer2003, wServer2003_R2,
    wVista, wVista_64, wServer2008, wServer2008_64,
    wServer2008_R2, wServer2008_R2_64, wSeven, wSeven_64,
................................................................................
  // more optimistic/realistic value ($100000 instead of default $10000)
  SystemInfo: TSystemInfo;
  /// the current Operating System information, as retrieved for the current process
  OSVersionInfo: TOSVersionInfoEx;
  /// the current Operating System version, as retrieved for the current process
  OSVersion: TWindowsVersion;






























{/ this function can be used to create a GDI compatible window, able to
  receive Windows Messages for fast local communication
  - will return 0 on failure (window name already existing e.g.), or
    the created HWND handle on success
  - it will call the supplied message handler defined for a given Windows Message:
    for instance, define such a method in any object definition:
  !  procedure WMCopyData(var Msg : TWMCopyData); message WM_COPYDATA; }
................................................................................
/// compatibility function, to be implemented according to the running OS
// - expect more or less the same result as the homonymous Win32 API function
// - will call the corresponding function in SynKylix.pas or SynFPCLinux.pas 
function GetTickCount64: Int64;

{$endif MSWINDOWS}

var
  /// global information about the current executable and computer
  // - this structure is initialized in this unit's initialization block below
  // - you can call SetExecutableVersion() with a custom version, if needed 
  ExeVersion: record
    /// the main executable name, without any path nor extension
    // - e.g. 'Test' for 'c:\pathto\Test.exe'
    ProgramName: RawUTF8;
    /// the main executable details, as used e.g. by TSynLog
    // - e.g. 'C:\Dev\lib\SQLite3\exe\TestSQL3.exe 0.0.0.0 (2011-03-29 11:09:06)'
    ProgramFullSpec: RawUTF8;
    /// the main executable file name (including full path)
    // - same as paramstr(0)
    ProgramFileName: TFileName;
    /// the main executable full path (excluding .exe file name)
    // - same as ExtractFilePath(paramstr(0))
    ProgramFilePath: TFileName;
    /// the full path of the running executable or library
    // - for an executable, same as paramstr(0)
    // - for a library, will contain the whole .dll file name
    InstanceFileName: TFileName;
    /// the current executable version
    Version: TFileVersion;
    /// the current computer host name
    Host: RawUTF8;
    /// the current computer user name
    User: RawUTF8;
  end;

/// initialize ExeVersion global variable, supplying a custom version number
// - by default, the version numbers will be retrieved at startup from the
// executable itself (if it was included at build time)
// - but you can use this function to set any custom version numbers
procedure SetExecutableVersion(aMajor,aMinor,aRelease: integer);

/// self-modifying code - change some memory buffer in the code segment
// - if Backup is not nil, it should point to a Size array of bytes, ready
// to contain the overridden code buffer, for further hook disabling
procedure PatchCode(Old,New: pointer; Size: integer; Backup: pointer=nil;
  LeaveUnprotected: boolean=false);

/// self-modifying code - change one PtrUInt in the code segment
................................................................................

var
  /// a global "Garbage collector", for some classes instances which must
  // live during whole main executable process
  // - used to avoid any memory leak with e.g. 'class var RecordProps', i.e.
  // some singleton or static objects
  // - to be used, e.g. as:
  // !  Version := TFileVersion.Create(InstanceFileName,DefaultVersion32);
  // !  GarbageCollector.Add(Version);
  GarbageCollector: TObjectList;

  /// set to TRUE when the global "Garbage collector" are beeing freed
  GarbageCollectorFreeing: boolean;

/// a global "Garbage collector" for some TObject global variables which must
................................................................................
  end else
    P := StrUInt64(P,val);
  result := P;
end;


// some minimal RTTI const and types

procedure Exchg(P1,P2: PAnsiChar; count: integer);
var c: AnsiChar;
begin
  while count>0 do begin
    dec(count);
    c := P1[count];
    P1[count] := P2[count];
    P2[count] := c;
  end;
end;

{$ifdef FPC}

type
  /// available type families for Free Pascal RTTI values
  // - values differs from Delphi, and are taken from FPC typinfo.pp unit
  // - here below, we defined tkLString instead of FPC tkAString to match
................................................................................
    jnz @1
    xor eax,eax
@z:
end;
{$endif}

function StringReplaceChars(const Source: RawUTF8; OldChar, NewChar: AnsiChar): RawUTF8;
var i,j,n: integer;
begin
  if (OldChar<>NewChar) and (Source<>'') then begin
    n := length(Source);
    for i := 0 to n-1 do
      if PAnsiChar(pointer(Source))[i]=OldChar then begin
        SetString(result,PAnsiChar(pointer(Source)),n);
        for j := i to n-1 do
          if PAnsiChar(pointer(Source))[j]=OldChar then
            PAnsiChar(pointer(result))[j] := NewChar;
        exit;
      end;
  end;
  result := Source;



end;

function PosI(uppersubstr: PUTF8Char; const str: RawUTF8): Integer;
var C: AnsiChar;
begin
  if uppersubstr<>nil then begin
    C := uppersubstr^;
................................................................................
    aWindow := 0;
    aWindowName := '';
    result := true;
  end else
    result := false;
end;



{$else}

const
  _SC_PAGE_SIZE = $1000;

{$endif MSWINDOWS}

{ TFileVersion }

constructor TFileVersion.Create(const aFileName: TFileName;
  aMajor,aMinor,aRelease: integer);
var M,D: word;
{$ifdef MSWINDOWS}
    Size, Size2: DWord;
    Pt: Pointer;
    Info: ^TVSFixedFileInfo;
    FileTime: TFILETIME;
    SystemTime: TSYSTEMTIME;
    tmp: TFileName;
{$endif}
begin
  Major := aMajor;
  Minor := aMinor;
  Release := aRelease;
  {$ifdef MSWINDOWS}
  if aFileName<>'' then begin
    // GetFileVersionInfo modifies the filename parameter data while parsing.
    // Copy the string const into a local variable to create a writeable copy.
    SetString(tmp,PChar(aFileName),length(aFileName));
    Size := GetFileVersionInfoSize(pointer(tmp), Size2);
    if Size>0 then begin
      GetMem(Pt, Size);
      try
        GetFileVersionInfo(pointer(aFileName), 0, Size, Pt);
        VerQueryValue(Pt, '\', pointer(Info), Size2);
        with Info^ do begin
          if Version32=0 then begin
            Major := dwFileVersionMS shr 16;
            Minor := word(dwFileVersionMS);
            Release := dwFileVersionLS shr 16;
          end;
          Build := word(dwFileVersionLS);
          BuildYear := 2010;
          if (dwFileDateLS<>0) and (dwFileDateMS<>0) then begin
            FileTime.dwLowDateTime:= dwFileDateLS; // built date from version info
            FileTime.dwHighDateTime:= dwFileDateMS;
            FileTimeToSystemTime(FileTime, SystemTime);
            fBuildDateTime := EncodeDate(
              SystemTime.wYear,SystemTime.wMonth,SystemTime.wDay);
          end;
        end;
      finally
        Freemem(Pt);
      end;
    end;
  end;
  {$endif}
  Main := IntToString(Major)+'.'+IntToString(Minor);
  fDetailed := Main+ '.'+IntToString(Release)+'.'+IntToString(Build);
  if fBuildDateTime=0 then  // get build date from file age
    fBuildDateTime := FileAgeToDateTime(aFileName);
  if fBuildDateTime<>0 then
    DecodeDate(fBuildDateTime,BuildYear,M,D);
end;

function TFileVersion.Version32: integer;
begin
  result := Major shl 16+Minor shl 8+Release;
end;

procedure SetExecutableVersion(aMajor,aMinor,aRelease: integer);
var setVersion,i: integer;
{$ifdef MSWINDOWS}
    Tmp: array[byte] of AnsiChar;
    TmpSize: cardinal;

{$else}
{$endif}
begin
  setVersion := aMajor shl 16+aMinor shl 8+aRelease;
  with ExeVersion do
  if Version<>nil then
    if Version.Version32=setVersion then
      exit else
      FreeAndNil(Version); // allow version number forcing
  with ExeVersion do
  if Version=nil then begin
    {$ifdef MSWINDOWS}
    ProgramFileName := paramstr(0);
    {$else}
    ProgramFileName := GetModuleName(hInstance);
    if ProgramFileName='' then
      ProgramFileName := ExpandFileName(paramstr(0));
    {$endif}
    ProgramFilePath := ExtractFilePath(ProgramFileName);
    if IsLibrary then
      InstanceFileName := GetModuleName(HInstance) else
      InstanceFileName := ProgramFileName;
    Version := TFileVersion.Create(InstanceFileName,aMajor,aMinor,aRelease);
    GarbageCollector.Add(Version);
    ProgramFullSpec := FormatUTF8('% % (%)',
      [ProgramFileName,Version.Detailed,DateTimeToIso8601(Version.BuildDateTime,True,' ')]);
    ProgramName := StringToUTF8(ExtractFileName(ProgramFileName));
    i := length(ProgramName);
    while i>0 do
      if ProgramName[i]='.' then begin
        SetLength(ProgramName,i-1);
        break;
      end else
      dec(i);
    {$ifdef MSWINDOWS}
    TmpSize := sizeof(Tmp);
    GetComputerNameA(Tmp,TmpSize);
    Host := Tmp;
    TmpSize := sizeof(Tmp);
    GetUserNameA(Tmp,TmpSize);
    User := Tmp;
    {$else}
    Host := GetHostName;
    {$ifdef KYLIX3}
    User := LibC.getpwuid(LibC.getuid)^.pw_name;
    {$endif}
    {$endif}





    if Host='' then
      Host := 'unknown';







    if User='' then























      User := 'unknown';
  end;
end;
























procedure PatchCode(Old,New: pointer; Size: integer; Backup: pointer=nil;
  LeaveUnprotected: boolean=false);
{$ifdef MSWINDOWS}
var RestoreProtection, Ignore: DWORD;
    i: integer;
................................................................................
  if VKind=dvArray then
    for result := 0 to VCount-1 do
      if VValue[result]=aValue then // rely on Variants.pas comparison
        exit;
  result := -1;
end;












procedure QuickSortDocVariant(names: PPointerArray; values: PVariantArray;
  L, R: PtrInt; Compare: TUTF8Compare);
var I, J, P: PtrInt;
    pivot, Tmp: pointer;
begin
  if L<R then
  repeat
................................................................................
  {$endif USEPACKAGES}
  {$endif CPUARM}
  {$endif FPC}
  InitSynCommonsConversionTables;
  {$ifdef MSWINDOWS}
  RetrieveSystemInfo;
  {$endif MSWINDOWS}
  SetExecutableVersion(0,0,0);
  // some type definition assertions
  Assert(SizeOf(TSynTableFieldType)=1); // as expected by TSynTableFieldProperties
  Assert(SizeOf(TSynTableFieldOptions)=1);
  {$ifndef NOVARIANTS}
  Assert(SizeOf(TSynTableData)=sizeof(TVarData));
  Assert(SizeOf(TDocVariantData)=sizeof(TVarData));
  {$endif NOVARIANTS}

finalization
  GarbageCollectorFree;
  if GlobalCriticalSectionInitialized then
    DeleteCriticalSection(GlobalCriticalSection);
end.

Changes to SynDBFirebird.pas.

905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
    Key: HKEY;
    Size: Cardinal;
    HR: Integer;
    CurrentDir: TFileName;
{$endif}
begin
  if aEmbedded then begin
    fLibName := ExtractFilePath(paramstr(0));
    if FileExists(LibName+FBLIBNAME[true]) then
      fLibName := LibName+FBLIBNAME[true] else
      fLibName := LibName+'Firebird\'+FBLIBNAME[true];
    if FileExists(fLibName) then begin
      {$ifdef MSWINDOWS}
      CurrentDir := GetCurrentDir;
      SetCurrentDir(ExtractFilePath(fLibName));






|







905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
    Key: HKEY;
    Size: Cardinal;
    HR: Integer;
    CurrentDir: TFileName;
{$endif}
begin
  if aEmbedded then begin
    fLibName := ExeVersion.ProgramFilePath;
    if FileExists(LibName+FBLIBNAME[true]) then
      fLibName := LibName+FBLIBNAME[true] else
      fLibName := LibName+'Firebird\'+FBLIBNAME[true];
    if FileExists(fLibName) then begin
      {$ifdef MSWINDOWS}
      CurrentDir := GetCurrentDir;
      SetCurrentDir(ExtractFilePath(fLibName));

Changes to SynDBOracle.pas.

1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
      if orhome<>'' then begin
        fLibraryPath := IncludeTrailingPathDelimiter(orhome)+'bin\oci.dll';
        fHandle := SafeLoadLibrary(fLibraryPath);
      end;
    end;
  end;
  if fHandle=0 then begin
    fLibraryPath := ExtractFilePath(paramstr(0))+'OracleInstantClient\oci.dll';
    fHandle := SafeLoadLibrary(fLibraryPath);
  end;
  if fHandle=0 then
    raise ESQLDBOracle.Create('Unable to find Oracle Client Interface (oci.dll)');
  P := @@ClientVersion;
  for i := 0 to High(OCI_ENTRIES) do begin
    P^ := GetProcAddress(fHandle,OCI_ENTRIES[i]);






|







1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
      if orhome<>'' then begin
        fLibraryPath := IncludeTrailingPathDelimiter(orhome)+'bin\oci.dll';
        fHandle := SafeLoadLibrary(fLibraryPath);
      end;
    end;
  end;
  if fHandle=0 then begin
    fLibraryPath := ExeVersion.ProgramFilePath+'OracleInstantClient\oci.dll';
    fHandle := SafeLoadLibrary(fLibraryPath);
  end;
  if fHandle=0 then
    raise ESQLDBOracle.Create('Unable to find Oracle Client Interface (oci.dll)');
  P := @@ClientVersion;
  for i := 0 to High(OCI_ENTRIES) do begin
    P^ := GetProcAddress(fHandle,OCI_ENTRIES[i]);

Changes to SynDBZEOS.pas.

672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
  if result='' then
    exit;
  if aServerName<>'' then
    result := result+'//'+aServerName;
  if aLibraryLocation<>'' then begin
    result := result+'?LibLocation=';
    if aLibraryLocationAppendExePath then
      result := result+StringToUTF8(ExtractFilePath(ParamStr(0)));
    result := result+StringToUTF8(aLibraryLocation);
  end;
end;


{ TSQLDBZEOSConnection }







|







672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
  if result='' then
    exit;
  if aServerName<>'' then
    result := result+'//'+aServerName;
  if aLibraryLocation<>'' then begin
    result := result+'?LibLocation=';
    if aLibraryLocationAppendExePath then
      result := result+StringToUTF8(ExeVersion.ProgramFilePath);
    result := result+StringToUTF8(aLibraryLocation);
  end;
end;


{ TSQLDBZEOSConnection }

Changes to SynLog.pas.

2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
....
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
....
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986


2987
2988
2989
2990
2991
2992
2993















2994
2995
2996
2997
2998

2999
3000
3001
3002
3003
3004
3005
....
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
....
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
        if aPath='' then begin
          aTime := FileAgeToDateTime(aOldLogFileName);
          if (aTime=0) or
             not DirectoryExists(ArchivePath+'log') and
             not CreateDir(ArchivePath+'log') then
            break;
          DecodeDate(aTime,Y,M,D);
          PCardinal(@tmp)^ := ord('l')+ord('o') shl 8+ord('g') shl 16+ord('\') shl 24;
          YearToPChar(Y,@tmp[4]);
          PWord(@tmp[8])^ := TwoDigitLookupW[M];
          PWord(@tmp[10])^ := ord('\');
          aPath := ArchivePath+Ansi7ToString(tmp,11);
        end;
        OnArchive(aOldLogFileName,aPath);
      until FindNext(SR)<>0;
    finally
      try
        OnArchive('',aPath); // mark no more .log file to archive -> close .zip
................................................................................
  if DebugHook<>0 then
    asm int 3 end; // force manual breakpoint if tests are run from the IDE
  {$endif}
end;

procedure TSynLog.LogFileHeader;
var WithinEvents: boolean;
{$ifdef MSWINDOWS}
    Env: PAnsiChar;
    P: PUTF8Char;
    L: Integer;
{$else}
    ExecutableName: string;
    uts: UtsName;
{$endif}
procedure NewLine;
begin
  if WithinEvents then begin
    fWriter.AddEndOfLine(sllNewRun);
    LogCurrentTime;
    fWriter.AddShort(LOG_LEVEL_TEXT[sllNewRun]);
  end else
................................................................................
begin
  if not QueryPerformanceFrequency(fFrequencyTimeStamp) then begin
    fFamily.HighResolutionTimeStamp := false;
    fFrequencyTimeStamp := 0;
  end else
    if (fFileRotationSize>0) or (fFileRotationNextHour<>0) then
      fFamily.HighResolutionTimeStamp := false;
  {$ifdef MSWINDOWS}
  ExeVersionRetrieve;
  {$endif}
  if InstanceMapFile=nil then
    GarbageCollectorFreeAndNil(InstanceMapFile,TSynMapFile.Create);
  WithinEvents := fWriter.WrittenBytes>0;
  // array of const is buggy under Delphi 5 :( -> use fWriter.Add*() below
  if WithinEvents then begin
    LogCurrentTime;
    fWriter.AddShort(LOG_LEVEL_TEXT[sllNewRun]);
    fWriter.AddChars('=',50);
    NewLine;
  end;
  {$ifdef MSWINDOWS}
  with ExeVersion, SystemInfo, OSVersionInfo, fWriter do begin
    AddString(ProgramFullSpec);
    NewLine;
    AddShort('Host=');  AddString(Host);
    AddShort(' User='); AddString(User);


    AddShort(' CPU=');  Add(dwNumberOfProcessors); Add('*');
    Add(wProcessorArchitecture); Add('-'); Add(wProcessorLevel); Add('-');
    Add(wProcessorRevision);
    AddShort(' OS='); Add(ord(OSVersion)); Add('.'); Add(wServicePackMajor);
    Add('='); Add(dwMajorVersion); Add('.'); Add(dwMinorVersion); Add('.');
    Add(dwBuildNumber);
    AddShort(' Wow64='); Add(integer(IsWow64));















    AddShort(' Freq='); Add(fFrequencyTimeStamp);
    if IsLibrary then begin
      AddShort(' Instance=');
      AddNoJSONEscapeString(InstanceFileName);
    end;

    NewLine;
    AddShort('Environment variables=');
    Env := GetEnvironmentStringsA;
    P := pointer(Env);
    while P^<>#0 do begin
      L := StrLen(P);
      if (L>0) and (P^<>'=') then begin
................................................................................
        AddNoJSONEscape(P,L);
        Add(#9);
      end;
      inc(P,L+1);
    end;
    FreeEnvironmentStringsA(Env);
    CancelLastChar; // trim last #9
    {$else}
  with fWriter do begin
    ExecutableName := GetModuleName(hInstance);
    if ExecutableName='' then
      ExecutableName := paramstr(0);
    if ExecutableName='' then
      AddShort('nomodulename') else
      AddNoJSONEscapeString(ExecutableName);
    AddShort(' unknown (');
    if ExecutableName='' then
      AddDateTime(now) else
      AddDateTime(FileAgeToDateTime(ExecutableName));
    Add(')');
    NewLine;
    AddShort('Host='); AddString(GetHostName);
    AddShort(' User=');
    {$ifdef KYLIX3}
    AddNoJSONEscape(LibC.getpwuid(LibC.getuid)^.pw_name);
    AddShort(' CPU=');
    Add(LibC.get_nprocs); Add('/'); Add(LibC.get_nprocs_conf);
    AddShort(' OS=');
    uname(uts);
    {$else}
    AddShort('unknown CPU=unknown OS=');
    FPUname(uts);
    {$endif}
    AddNoJSONEscape(@uts.sysname); Add('-'); AddNoJSONEscape(@uts.release);
    AddReplace(@uts.version,' ','-');
    AddShort(' Wow64=0 Freq=');
    Add(fFrequencyTimeStamp);
    {$endif}
    NewLine;
    AddClassName(self.ClassType);
    AddShort(' '+SYNOPSE_FRAMEWORK_FULLVERSION+' ');
    AddDateTime(Now);
    if WithinEvents then
      AddEndOfLine(sllNone) else
................................................................................
end;

procedure TSynLog.ComputeFileName;
var timeNow,hourRotate,timeBeforeRotate: TDateTime;
begin
  fFileName := fFamily.fCustomFileName;
  if fFileName='' then begin
    {$ifdef MSWINDOWS}
    ExeVersionRetrieve;
    fFileName := UTF8ToString(ExeVersion.ProgramName);
    if fFamily.IncludeComputerNameInFileName then
      fFileName := fFileName+' ('+UTF8ToString(ExeVersion.Host)+')';
    {$else}
    fFileName := GetFileNameWithoutExt(ExtractFileName(ParamStr(0)));
    {$endif}
  end;
  fFileRotationSize := 0;
  if fFamily.fRotateFileCount>0 then begin
    if fFamily.fRotateFileSize>0 then
      fFileRotationSize := fFamily.fRotateFileSize shl 10; // size KB -> B
    if fFamily.fRotateFileAtHour in [0..23] then begin
      hourRotate := EncodeTime(fFamily.fRotateFileAtHour,0,0,0);






|


|







 







|



|
<

|







 







<
<
<










<
|




>
>
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<



<
<
<







2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
....
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948

2949
2950
2951
2952
2953
2954
2955
2956
2957
....
2960
2961
2962
2963
2964
2965
2966



2967
2968
2969
2970
2971
2972
2973
2974
2975
2976

2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
....
3019
3020
3021
3022
3023
3024
3025






























3026
3027
3028
3029
3030
3031
3032
....
3240
3241
3242
3243
3244
3245
3246


3247
3248
3249



3250
3251
3252
3253
3254
3255
3256
        if aPath='' then begin
          aTime := FileAgeToDateTime(aOldLogFileName);
          if (aTime=0) or
             not DirectoryExists(ArchivePath+'log') and
             not CreateDir(ArchivePath+'log') then
            break;
          DecodeDate(aTime,Y,M,D);
          PCardinal(@tmp)^ := ord('l')+ord('o') shl 8+ord('g') shl 16+ord(PathDelim) shl 24;
          YearToPChar(Y,@tmp[4]);
          PWord(@tmp[8])^ := TwoDigitLookupW[M];
          PWord(@tmp[10])^ := ord(PathDelim);
          aPath := ArchivePath+Ansi7ToString(tmp,11);
        end;
        OnArchive(aOldLogFileName,aPath);
      until FindNext(SR)<>0;
    finally
      try
        OnArchive('',aPath); // mark no more .log file to archive -> close .zip
................................................................................
  if DebugHook<>0 then
    asm int 3 end; // force manual breakpoint if tests are run from the IDE
  {$endif}
end;

procedure TSynLog.LogFileHeader;
var WithinEvents: boolean;
    {$ifdef MSWINDOWS}
    Env: PAnsiChar;
    P: PUTF8Char;
    L: Integer;
    {$else}

    uts: UtsName;
    {$endif}
procedure NewLine;
begin
  if WithinEvents then begin
    fWriter.AddEndOfLine(sllNewRun);
    LogCurrentTime;
    fWriter.AddShort(LOG_LEVEL_TEXT[sllNewRun]);
  end else
................................................................................
begin
  if not QueryPerformanceFrequency(fFrequencyTimeStamp) then begin
    fFamily.HighResolutionTimeStamp := false;
    fFrequencyTimeStamp := 0;
  end else
    if (fFileRotationSize>0) or (fFileRotationNextHour<>0) then
      fFamily.HighResolutionTimeStamp := false;



  if InstanceMapFile=nil then
    GarbageCollectorFreeAndNil(InstanceMapFile,TSynMapFile.Create);
  WithinEvents := fWriter.WrittenBytes>0;
  // array of const is buggy under Delphi 5 :( -> use fWriter.Add*() below
  if WithinEvents then begin
    LogCurrentTime;
    fWriter.AddShort(LOG_LEVEL_TEXT[sllNewRun]);
    fWriter.AddChars('=',50);
    NewLine;
  end;

  with ExeVersion, fWriter do begin
    AddString(ProgramFullSpec);
    NewLine;
    AddShort('Host=');  AddString(Host);
    AddShort(' User='); AddString(User);
    {$ifdef MSWINDOWS}
    with SystemInfo, OSVersionInfo do begin
      AddShort(' CPU=');  Add(dwNumberOfProcessors); Add('*');
      Add(wProcessorArchitecture); Add('-'); Add(wProcessorLevel); Add('-');
      Add(wProcessorRevision);
      AddShort(' OS='); Add(ord(OSVersion)); Add('.'); Add(wServicePackMajor);
      Add('='); Add(dwMajorVersion); Add('.'); Add(dwMinorVersion); Add('.');
      Add(dwBuildNumber);
      AddShort(' Wow64='); Add(integer(IsWow64));
    end;
    {$else}
    {$ifdef KYLIX3}
    AddShort(' CPU=');
    Add(LibC.get_nprocs); Add('/'); Add(LibC.get_nprocs_conf);
    AddShort(' OS=');
    uname(uts);
    {$else}
    AddShort(' CPU=unknown OS=');
    FPUname(uts);
    {$endif}
    AddNoJSONEscape(@uts.sysname); Add('-'); AddNoJSONEscape(@uts.release);
    AddReplace(@uts.version,' ','-');
    AddShort(' Wow64=0');
    {$endif}
    AddShort(' Freq='); Add(fFrequencyTimeStamp);
    if IsLibrary then begin
      AddShort(' Instance=');
      AddNoJSONEscapeString(InstanceFileName);
    end;
    {$ifdef MSWINDOWS}
    NewLine;
    AddShort('Environment variables=');
    Env := GetEnvironmentStringsA;
    P := pointer(Env);
    while P^<>#0 do begin
      L := StrLen(P);
      if (L>0) and (P^<>'=') then begin
................................................................................
        AddNoJSONEscape(P,L);
        Add(#9);
      end;
      inc(P,L+1);
    end;
    FreeEnvironmentStringsA(Env);
    CancelLastChar; // trim last #9






























    {$endif}
    NewLine;
    AddClassName(self.ClassType);
    AddShort(' '+SYNOPSE_FRAMEWORK_FULLVERSION+' ');
    AddDateTime(Now);
    if WithinEvents then
      AddEndOfLine(sllNone) else
................................................................................
end;

procedure TSynLog.ComputeFileName;
var timeNow,hourRotate,timeBeforeRotate: TDateTime;
begin
  fFileName := fFamily.fCustomFileName;
  if fFileName='' then begin


    fFileName := UTF8ToString(ExeVersion.ProgramName);
    if fFamily.IncludeComputerNameInFileName then
      fFileName := fFileName+' ('+UTF8ToString(ExeVersion.Host)+')';



  end;
  fFileRotationSize := 0;
  if fFamily.fRotateFileCount>0 then begin
    if fFamily.fRotateFileSize>0 then
      fFileRotationSize := fFamily.fRotateFileSize shl 10; // size KB -> B
    if fFamily.fRotateFileAtHour in [0..23] then begin
      hourRotate := EncodeTime(fFamily.fRotateFileAtHour,0,0,0);

Changes to SynSQLite3.pas.

2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
....
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
....
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
....
3815
3816
3817
3818
3819
3820
3821
3822

3823
3824
3825
3826
3827
3828
3829
....
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
....
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
....
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
....
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
....
4074
4075
4076
4077
4078
4079
4080
4081

4082
4083
4084
4085
4086
4087
4088
....
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
....
4807
4808
4809
4810
4811
4812
4813
4814

4815
4816

4817
4818
4819
4820

4821
4822


4823
4824
4825


4826
4827
4828
4829
4830
4831
4832
    /// hashing wrapper associated to the Cache[] array
    Caches: TDynArrayHashed;
    /// the associated SQLite3 database instance
    DB: TSQLite3DB;
    /// intialize the cache
    procedure Init(aDB: TSQLite3DB);
    /// add or retrieve a generic SQL (with ? parameters) statement from cache
    function Prepare(const GenericSQL: RawUTF8): PSQLRequest;
    // used internaly to release all prepared statements from Cache[]
    procedure ReleaseAllDBStatements;
  end;

  /// those classes can be used to define custom SQL functions inside a TSQLDataBase
  TSQLDataBaseSQLFunction = class
  protected
................................................................................
  if (self=nil) or (DB=0) then
    result := 0 else
    try
      Lock;
      result := sqlite3.changes(DB);
      {$ifdef WITHLOG}
      if fLog<>nil then
        fLog.Add.Log(sllDB,'LastChangeCount=%',result,self);
      {$endif}
    finally
      UnLock;
    end;
end;

procedure TSQLDataBase.GetTableNames(var Names: TRawUTF8DynArray);
................................................................................
  EnterCriticalSection(fLock); // cache access is also protected by fLock
  try
    if isSelect(pointer(aSQL)) then begin
      result := fCache.Find(aSQL,aResultCount); // try to get JSON result from cache
      if result<>'' then begin
        {$ifdef WITHLOG}
        if fLog<>nil then begin
          fLog.Add.Log(sllSQL,aSQL,self,2048);
          fLog.Add.Log(sllCache,'from cache',self);
          fLog.Add.Log(sllResult,result,self,fLogResultMaximumSize);
        end;
        {$endif}
        LeaveCriticalSection(fLock); // found in cache -> leave critical section
      end;
    end else begin
      // UPDATE, INSERT or any non SELECT statement
................................................................................
    Backup: TSQLite3Backup;
begin
  result := false;
  if (self=nil) or (BackupFileName='') or not Assigned(sqlite3.backup_init) or
     (fBackupBackgroundInProcess<>nil) then
    exit;
  {$ifdef WITHLOG}
  fLog.Add.Log(sllDB,self);

  {$endif}
  if FileExists(BackupFileName) then
    if not DeleteFile(BackupFileName) then
      exit;
  Dest := TSQLDatabase.Create(BackupFileName,aPassword);
  Backup := sqlite3.backup_init(Dest.DB,'main',DB,'main');
  if Backup=0 then begin
................................................................................

function TSQLDataBase.DBClose: integer;
begin
  result := SQLITE_OK;
  if (self=nil) or (fDB=0) then
    exit;
  {$ifdef WITHLOG}
  fLog.Enter.Log(sllDB,self);
  {$endif}
  if (sqlite3=nil) or not Assigned(sqlite3.close) then
    raise ESQLite3Exception.Create('DBClose called with no sqlite3 global');
  if fBackupBackgroundInProcess<>nil then
    BackupBackgroundWaitUntilFinished;
  result := sqlite3.close(fDB);
  fDB := 0;
................................................................................
  if fOpenV2Flags<>(SQLITE_OPEN_READWRITE or SQLITE_OPEN_CREATE) then
    result := sqlite3.open_v2(pointer(utf8),fDB,fOpenV2Flags,nil) else
  {$endif}
    result := sqlite3.open(pointer(utf8),fDB);
  if result<>SQLITE_OK then begin
    {$ifdef WITHLOG}
    if Log<>nil then
      Log.Log(sllError,'open ("%") failed with error % (%): %',
        [utf8,sqlite3_resultToErrorText(result),result,sqlite3.errmsg(fDB)]);
    {$endif}
    sqlite3.close(fDB); // should always be closed, even on failure
    fDB := 0;
    exit;
  end;
  if Assigned(sqlite3.key) and (fPassword<>'') and
................................................................................
  // reallocate all TSQLDataBaseSQLFunction for re-Open (TSQLRestServerDB.Backup)
  for i := 0 to fSQLFunctions.Count-1 do
    TSQLDataBaseSQLFunction(fSQLFunctions.List[i]).CreateFunction(DB);
  // tune up execution speed
  if not fIsMemory then
    CacheSize := 10000;
  {$ifdef WITHLOG}
  Log.Log(sllDB,self);
  {$endif}
end;

function TSQLDataBase.GetUserVersion: cardinal;
begin
  result := ExecuteNoExceptionInt64('PRAGMA user_version');
end;
................................................................................
procedure TSQLDataBase.CacheFlush;
begin
  if self=nil then
    exit;
  if InternalState<>nil then
    inc(InternalState^);
  if fCache.Reset then
  {$ifdef WITHLOG}
    if fLog<>nil then
      fLog.Add.Log(sllCache,'cache flushed',self);
  {$endif}
end;

procedure TSQLDataBase.RegisterSQLFunction(aFunction: TSQLDataBaseSQLFunction);
var i: integer;
begin
  if (self=nil) or (aFunction=nil) then
    exit;
................................................................................
    if (FunctionParametersCount=aFunction.FunctionParametersCount) and
       IdemPropNameU(FunctionName,aFunction.FunctionName) then begin
      aFunction.Free;
      exit; // already registered with the same name and parameters count
    end;
  {$ifdef WITHLOG}
  if fLog<>nil then
    fLog.Add.Log(sllDB,'RegisterSQLFunction '+aFunction.FunctionName,self);

  {$endif}
  fSQLFunctions.Add(aFunction);
  if DB<>0 then
    // DB already opened -> register this custom function
    aFunction.CreateFunction(DB);
end;

................................................................................
  if aFunctionName='' then
    fSQLName := RawUTF8(copy(ClassName,2,maxInt)) else
    fSQLName := aFunctionName;
end;

function TSQLDataBaseSQLFunction.CreateFunction(DB: TSQLite3DB): Integer;
begin
  if self<>nil then begin
    result := sqlite3.create_function(DB,pointer(fSQLName),
      FunctionParametersCount,SQLITE_ANY,self,fInternalFunction,nil,nil);
    {$ifdef WITHLOGSQLFUNCTION}
    if (result<>SQLITE_OK) and (fLog<>nil) then
      fLog.Add.Log(sllError,'register SQL function failed: '+FunctionName,self);
    {$endif}
  end else
    result := SQLITE_ERROR;
end;


{ TSQLDataBaseSQLFunctionDynArray }

procedure InternalSQLFunctionDynArrayBlob(Context: TSQLite3FunctionContext;
................................................................................

procedure TSQLStatementCached.Init(aDB: TSQLite3DB);
begin
  Caches.Init(TypeInfo(TSQLStatementCacheDynArray),Cache,nil,nil,nil,@Count);
  DB := aDB;
end;

function TSQLStatementCached.Prepare(const GenericSQL: RawUTF8): PSQLRequest;

var added: boolean;
    ndx: integer;

begin
  ndx := Caches.FindHashedForAdding(GenericSQL,added);
  with Cache[ndx] do begin
    if added then begin

      StatementSQL := GenericSQL;
      Statement.Prepare(DB,GenericSQL);


    end else begin
      //Statement.BindReset; // slow down the process, and is not mandatory
      Statement.Reset;


    end;
    result := @Statement;
  end;
end;

procedure TSQLStatementCached.ReleaseAllDBStatements;
var i: integer;






|







 







|







 







|
<







 







|
>







 







|







 







|







 







|







 







|

|
|







 







|
>







 







|

|
<
<
<
<
<







 







|
>


>




>


>
>



>
>







2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
....
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
....
3721
3722
3723
3724
3725
3726
3727
3728

3729
3730
3731
3732
3733
3734
3735
....
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
....
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
....
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
....
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
....
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
....
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
....
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754





4755
4756
4757
4758
4759
4760
4761
....
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
    /// hashing wrapper associated to the Cache[] array
    Caches: TDynArrayHashed;
    /// the associated SQLite3 database instance
    DB: TSQLite3DB;
    /// intialize the cache
    procedure Init(aDB: TSQLite3DB);
    /// add or retrieve a generic SQL (with ? parameters) statement from cache
    function Prepare(const GenericSQL: RawUTF8; WasPrepared: PBoolean=nil): PSQLRequest;
    // used internaly to release all prepared statements from Cache[]
    procedure ReleaseAllDBStatements;
  end;

  /// those classes can be used to define custom SQL functions inside a TSQLDataBase
  TSQLDataBaseSQLFunction = class
  protected
................................................................................
  if (self=nil) or (DB=0) then
    result := 0 else
    try
      Lock;
      result := sqlite3.changes(DB);
      {$ifdef WITHLOG}
      if fLog<>nil then
        fLog.Add.Log(sllDB,'% LastChangeCount=%',[FileNameWithoutPath,result],self);
      {$endif}
    finally
      UnLock;
    end;
end;

procedure TSQLDataBase.GetTableNames(var Names: TRawUTF8DynArray);
................................................................................
  EnterCriticalSection(fLock); // cache access is also protected by fLock
  try
    if isSelect(pointer(aSQL)) then begin
      result := fCache.Find(aSQL,aResultCount); // try to get JSON result from cache
      if result<>'' then begin
        {$ifdef WITHLOG}
        if fLog<>nil then begin
          fLog.Add.Log(sllSQL,'from cache % %',[FileNameWithoutPath,aSQL],self);

          fLog.Add.Log(sllResult,result,self,fLogResultMaximumSize);
        end;
        {$endif}
        LeaveCriticalSection(fLock); // found in cache -> leave critical section
      end;
    end else begin
      // UPDATE, INSERT or any non SELECT statement
................................................................................
    Backup: TSQLite3Backup;
begin
  result := false;
  if (self=nil) or (BackupFileName='') or not Assigned(sqlite3.backup_init) or
     (fBackupBackgroundInProcess<>nil) then
    exit;
  {$ifdef WITHLOG}
  fLog.Add.Log(sllDB,'BackupBackground("%") started on %',
    [BackupFileName,FileNameWithoutPath],self);
  {$endif}
  if FileExists(BackupFileName) then
    if not DeleteFile(BackupFileName) then
      exit;
  Dest := TSQLDatabase.Create(BackupFileName,aPassword);
  Backup := sqlite3.backup_init(Dest.DB,'main',DB,'main');
  if Backup=0 then begin
................................................................................

function TSQLDataBase.DBClose: integer;
begin
  result := SQLITE_OK;
  if (self=nil) or (fDB=0) then
    exit;
  {$ifdef WITHLOG}
  fLog.Enter.Log(sllDB,'closing "%"',[FileName],self);
  {$endif}
  if (sqlite3=nil) or not Assigned(sqlite3.close) then
    raise ESQLite3Exception.Create('DBClose called with no sqlite3 global');
  if fBackupBackgroundInProcess<>nil then
    BackupBackgroundWaitUntilFinished;
  result := sqlite3.close(fDB);
  fDB := 0;
................................................................................
  if fOpenV2Flags<>(SQLITE_OPEN_READWRITE or SQLITE_OPEN_CREATE) then
    result := sqlite3.open_v2(pointer(utf8),fDB,fOpenV2Flags,nil) else
  {$endif}
    result := sqlite3.open(pointer(utf8),fDB);
  if result<>SQLITE_OK then begin
    {$ifdef WITHLOG}
    if Log<>nil then
      Log.Log(sllError,'sqlite3_open ("%") failed with error % (%): %',
        [utf8,sqlite3_resultToErrorText(result),result,sqlite3.errmsg(fDB)]);
    {$endif}
    sqlite3.close(fDB); // should always be closed, even on failure
    fDB := 0;
    exit;
  end;
  if Assigned(sqlite3.key) and (fPassword<>'') and
................................................................................
  // reallocate all TSQLDataBaseSQLFunction for re-Open (TSQLRestServerDB.Backup)
  for i := 0 to fSQLFunctions.Count-1 do
    TSQLDataBaseSQLFunction(fSQLFunctions.List[i]).CreateFunction(DB);
  // tune up execution speed
  if not fIsMemory then
    CacheSize := 10000;
  {$ifdef WITHLOG}
  Log.Log(sllDB,'"%" database file opened',[FileName],self);
  {$endif}
end;

function TSQLDataBase.GetUserVersion: cardinal;
begin
  result := ExecuteNoExceptionInt64('PRAGMA user_version');
end;
................................................................................
procedure TSQLDataBase.CacheFlush;
begin
  if self=nil then
    exit;
  if InternalState<>nil then
    inc(InternalState^);
  if fCache.Reset then
   {$ifdef WITHLOG}
    if fLog<>nil then
      fLog.Add.Log(sllCache,'% cache flushed',[FileNameWithoutPath],self);
    {$endif}
end;

procedure TSQLDataBase.RegisterSQLFunction(aFunction: TSQLDataBaseSQLFunction);
var i: integer;
begin
  if (self=nil) or (aFunction=nil) then
    exit;
................................................................................
    if (FunctionParametersCount=aFunction.FunctionParametersCount) and
       IdemPropNameU(FunctionName,aFunction.FunctionName) then begin
      aFunction.Free;
      exit; // already registered with the same name and parameters count
    end;
  {$ifdef WITHLOG}
  if fLog<>nil then
    fLog.Add.Log(sllDB,'% RegisterSQLFunction("%") %',
      [FileNameWithoutPath,aFunction.FunctionName],self);
  {$endif}
  fSQLFunctions.Add(aFunction);
  if DB<>0 then
    // DB already opened -> register this custom function
    aFunction.CreateFunction(DB);
end;

................................................................................
  if aFunctionName='' then
    fSQLName := RawUTF8(copy(ClassName,2,maxInt)) else
    fSQLName := aFunctionName;
end;

function TSQLDataBaseSQLFunction.CreateFunction(DB: TSQLite3DB): Integer;
begin
  if self<>nil then 
    result := sqlite3.create_function(DB,pointer(fSQLName),
      FunctionParametersCount,SQLITE_ANY,self,fInternalFunction,nil,nil) else





    result := SQLITE_ERROR;
end;


{ TSQLDataBaseSQLFunctionDynArray }

procedure InternalSQLFunctionDynArrayBlob(Context: TSQLite3FunctionContext;
................................................................................

procedure TSQLStatementCached.Init(aDB: TSQLite3DB);
begin
  Caches.Init(TypeInfo(TSQLStatementCacheDynArray),Cache,nil,nil,nil,@Count);
  DB := aDB;
end;

function TSQLStatementCached.Prepare(const GenericSQL: RawUTF8;
  WasPrepared: PBoolean): PSQLRequest;
var added: boolean;
    ndx: integer;
    Timer: TPrecisionTimer;
begin
  ndx := Caches.FindHashedForAdding(GenericSQL,added);
  with Cache[ndx] do begin
    if added then begin
      Timer.Start;
      StatementSQL := GenericSQL;
      Statement.Prepare(DB,GenericSQL);
      if WasPrepared<>nil then
        WasPrepared^ := true;
    end else begin
      //Statement.BindReset; // slow down the process, and is not mandatory
      Statement.Reset;
      if WasPrepared<>nil then
        WasPrepared^ := false;
    end;
    result := @Statement;
  end;
end;

procedure TSQLStatementCached.ReleaseAllDBStatements;
var i: integer;

Changes to SynSelfTests.pas.

389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
....
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
....
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
....
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
....
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
....
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
....
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
....
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
....
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974

6975
6976
6977
6978
6979
6980
6981
....
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
....
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031

7032
7033
7034
7035
7036
7037
7038
7039
....
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
....
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
....
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
....
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
.....
10965
10966
10967
10968
10969
10970
10971

10972
10973
10974
10975
10976
10977
10978
10979
.....
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
    /// release used instances and memory
    procedure CleanUp; override;
  published
    /// direct LZ77 deflate/inflate functions
    procedure InMemoryCompression;
    /// .gzip archive handling
    procedure GZIPFormat;
    {$ifdef MSWINDOWS}
    /// .zip archive handling
    procedure ZIPFormat;
    {$endif}
    /// SynLZO internal format
    procedure _SynLZO;
    /// SynLZ internal format
    procedure _SynLZ;
................................................................................
    Check(T.AddField('bool',tftBoolean)=nil);
    Check(T.AddField('double',tftDouble)<>nil);
    Check(T.AddField('varint',tftVarUInt32)<>nil);
    Check(T.AddField('text',tftUTF8,[tfoUnique])<>nil);
    Check(T.AddField('ansi',tftWinAnsi,[])<>nil);
    Check(T.AddField('currency',tftCurrency)<>nil);
    Test;
    FN := ChangeFileExt(paramstr(0),'.syntable');
    DeleteFile(FN);
    W := TFileBufferWriter.Create(FN); // manual storage of TSynTable header
    try
      T.SaveTo(W);
      W.Flush;
    finally
      W.Free;
................................................................................
    fFileVersions: TFVs;
    class function FVReader(P: PUTF8Char; var aValue;
      out aValid: Boolean): PUTF8Char;
    class procedure FVWriter(const aWriter: TTextWriter; const aValue);
    class function FVReader2(P: PUTF8Char; var aValue;
      out aValid: Boolean): PUTF8Char;
    class procedure FVWriter2(const aWriter: TTextWriter; const aValue);
    {$ifdef MSWINDOWS}
    class function FVClassReader(const aValue: TObject; aFrom: PUTF8Char;
      var aValid: Boolean; aOptions: TJSONToObjectOptions): PUTF8Char;
    class procedure FVClassWriter(const aSerializer: TJSONSerializer;
      aValue: TObject; aOptions: TTextWriterWriteObjectOptions);
    {$endif}
  published
    property Ints: TIntegerDynArray read fInts write fInts;
    property TimeLog: TTimeLogDynArray read fTimeLog write fTimeLog;
    property FileVersion: TFVs read fFileVersions write fFileVersions;
  end;


................................................................................
class procedure TCollTstDynArray.FVWriter2(const aWriter: TTextWriter; const aValue);
var V: TFV absolute aValue;
begin
  aWriter.AddJSONEscape(['Major',V.Major,'Minor',V.Minor,'Release',V.Release,
    'Build',V.Build,'Main',V.Main,'Detailed',V.Detailed]);
end;

{$ifdef MSWINDOWS}

class function TCollTstDynArray.FVClassReader(const aValue: TObject; aFrom: PUTF8Char;
  var aValid: Boolean; aOptions: TJSONToObjectOptions): PUTF8Char;
var V: TFileVersion absolute aValue;
    Values: TPUtf8CharDynArray;
begin // '{"Major":2,"Minor":2002,"Release":3002,"Build":4002,"Main":"2","BuildDateTime":"1911-03-15"}'
  result := JSONDecode(aFrom,['Major','Minor','Release','Build','Main','BuildDateTime'],Values);
  aValid := (result<>nil);
................................................................................
  aValue: TObject; aOptions: TTextWriterWriteObjectOptions);
var V: TFileVersion absolute aValue;
begin
  aSerializer.AddJSONEscape(['Major',V.Major,'Minor',V.Minor,'Release',V.Release,
    'Build',V.Build,'Main',V.Main,'BuildDateTime',DateTimeToIso8601Text(V.BuildDateTime)]);
end;

{$endif MSWINDOWS}


{ TCollTests }

function TCollTests.Add: TCollTest;
begin
  result := inherited Add as TCollTest;
end;
................................................................................
      Check(Main=IntToStr(i));
      Check(Detailed=IntToStr(i+1000));
    end;
  finally
    CA.Free;
  end;
end;
{$ifdef MSWINDOWS}
procedure TFileVersionTest(Full: boolean);
var V,F: TFileVersion;
    J: RawUTF8;
    i: integer;
    Valid: boolean;
begin
  V := TFileVersion.Create('',0);
  F := TFileVersion.Create('',0);
  try
    for i := 1 to 1000 do begin
      if Full then begin
        V.Major := i;
        V.Minor := i+2000;
        V.Release := i+3000;
        V.Build := i+4000;
................................................................................
      CheckSame(V.BuildDateTime,F.BuildDateTime);
    end;
  finally
    F.Free;
    V.Free;
  end;
end;
{$endif}
{$endif}
{$endif}
procedure ABCD;
begin
  Check(Parser.Root.NestedProperty[0].PropertyName='A');
  Check(Parser.Root.NestedProperty[0].PropertyType=ptInteger);
  Check(Parser.Root.NestedProperty[1].PropertyName='B');
................................................................................
  TTextWriter.RegisterCustomJSONSerializer(TypeInfo(TFVs),
    TCollTstDynArray.FVReader,TCollTstDynArray.FVWriter);
  TCollTstDynArrayTest;
  TTextWriter.RegisterCustomJSONSerializer(TypeInfo(TFVs),
    TCollTstDynArray.FVReader2,TCollTstDynArray.FVWriter2);
  TCollTstDynArrayTest;
  // (custom) class serialization
  {$ifdef MSWINDOWS}
  TFileVersionTest(false);
  TJSONSerializer.RegisterCustomSerializer(TFileVersion,
    TCollTstDynArray.FVClassReader,TCollTstDynArray.FVClassWriter);
  TFileVersionTest(true);
  TJSONSerializer.RegisterCustomSerializer(TFileVersion,nil,nil);
  TFileVersionTest(false);
  {$endif MSWINDOWS}
{$endif DELPHI5OROLDER}
{$endif LVCL}
  // test TJSONRecordTextDefinition parsing
  Parser := TJSONRecordTextDefinition.FromCache(nil,'Int: double');
  Check(Length(Parser.Root.NestedProperty)=1);
  Check(Parser.Root.NestedProperty[0].PropertyName='Int');
  Check(Parser.Root.NestedProperty[0].PropertyType=ptDouble);
................................................................................
var comp: Integer;
    tmp: RawByteString;
begin
  Check(CRC32string('TestCRC32')=$2CB8CDF3);
  tmp := RawByteString(Ident);
  for comp := 0 to 9 do
    Check(UnCompressString(CompressString(tmp,False,comp))=tmp);
  Data := StringFromFile(ParamStr(0));
  Check(UnCompressString(CompressString(Data,False,6))=Data);
end;


{$ifdef MSWINDOWS}

procedure TTestCompression.ZipFormat;
var FN: TFileName;

    S: TRawByteStringStream;
procedure Test(Z: TZipRead; aCount: integer);
var i: integer;
    tmp: RawByteString;
    crc: Cardinal;
begin
  with Z do
................................................................................
    i := NameToIndex('REp2\ident.gz');
    Check(i=1);
    crc := crc32(0,M.Memory,M.Position);
    Check(Entry[i].infoLocal^.zcrc32=crc);
    tmp := UnZip(i);
    Check(tmp<>'');
    Check(crc32(0,pointer(tmp),length(tmp))=crc);
    i := NameToIndex(ExtractFileName(paramstr(0)));
    Check(i=2);
    Check(UnZip(i)=Data);
    Check(Entry[i].infoLocal^.zcrc32=crc32(0,pointer(Data),length(Data)));
    i := NameToIndex('REp2\ident2.gz');
    Check(i=3);
    Check(Entry[i].infoLocal^.zcrc32=crc);
    tmp := UnZip(i);
................................................................................
  with Z do
  try
    AddDeflated('rep1\one.exe',pointer(Data),length(Data));
    Check(Count=1);
    AddDeflated('rep2\ident.gz',M.Memory,M.Position);
    Check(Count=2);
    if Z is TZipWrite then
      TZipWrite(Z).AddDeflated(ParamStr(0)) else
      Z.AddDeflated(ExtractFileName(paramstr(0)),pointer(Data),length(Data));
    Check(Count=3,'direct zip file');
    AddStored('rep2\ident2.gz',M.Memory,M.Position);
    Check(Count=4);
  finally
    Free;
  end;
end;
begin

  FN := ChangeFileExt(paramstr(0),'.zip');
  Prepare(TZipWrite.Create(FN));
  Test(TZipRead.Create(FN),4);
  S := TRawByteStringStream.Create;
  try
    Prepare(TZipWriteToStream.Create(S));
    Test(TZipRead.Create(pointer(S.DataString),length(S.DataString)),4);
  finally
................................................................................
  finally
    Free;
  end;
  Test(TZipRead.Create(FN),5);
  DeleteFile(FN);
end;

{$endif MSWINDOWS}

procedure TTestCompression._SynLZO;
var s,t: AnsiString;
    i: integer;
begin
  for i := 0 to 1000 do begin
    t := RandomString(i*8);
................................................................................
  Value[10] := #$E9;
  Value[16] := #$E7;
  Value[17] := #$E0;
  Check(not IsBase64(Value));
  Check(Base64Encode(Value)=Value64);
  Check(BinToBase64(Value)=Value64);
  Check(IsBase64(Value64));
  tmp := StringFromFile(paramstr(0));
  b64 := Base64Encode(tmp);
  Check(IsBase64(b64));
  Check(Base64Decode(b64)=tmp);
  Check(BinToBase64(tmp)=b64);
  Check(Base64ToBin(b64)=tmp);
  tmp := '';
  for i := 1 to 1998 do begin
................................................................................
        WS := 'Texte accentue n.'+IntToString(i);
        PWordArray(WS)^[13] := 233;
        PWordArray(WS)^[16] := 176;
        Canvas.TextOutW(100,y,pointer(WS));
        dec(y,9+i);
      end;
      SaveToStream(MS,FIXED_DATE);
      //MS.SaveToFile(ChangeFileExt(paramstr(0),'.pdf'));
      Check(Hash32(MS.Memory,MS.Position)=Hash[embed]);
      if not embed then begin
        if CharSet<>ANSI_CHARSET then
          break; // StandardFontsReplace will work only with ANSI code page
        NewDoc;
        MS.Clear;
      end;
................................................................................
      finally
        MF.Free;
      end;
      MS.Clear;
      SaveToStream(MS,FIXED_DATE);
      // force constant Arial,Bold and Tahoma FontBBox
      SetString(s,PAnsiChar(MS.Memory),MS.Position);
      MS.SaveToFile(ChangeFileExt(paramstr(0),'.pdf'));
      if (GetACP<>1252) {$ifdef CPU64}or true{$endif} then
        Check(length(s)>6500) else begin
        i := PosEx('/FontBBox[',s);
        if CheckFailed(i=5580) then exit;
        fillchar(s[i],32,32);
        j := PosEx('/FontBBox[',s);
        if CheckFailed(j=5910) then exit;
................................................................................


{ TServicePerThread }

constructor TServicePerThread.Create;
begin
  inherited;

  fThreadIDAtCreation := {$ifdef MSWINDOWS}Windows.{$else}SynCommons.{$endif}GetCurrentThreadID;
end;

function TServicePerThread.GetCurrentThreadID: cardinal;
begin
  result := {$ifdef MSWINDOWS}Windows.{$else}SynCommons.{$endif}GetCurrentThreadID;
  with PServiceRunningContext(@ServiceContext)^ do
    if Request<>nil then
................................................................................
    Ints[1] := i2;
    SetLength(Str2,3);
    Str2[0] := 'ABC';
    Str2[1] := 'DEF';
    Str2[2] := 'GHIJK';
    fillchar(Rec1,sizeof(Rec1),0);
    Rec1.Features := [vtTransaction,vtSavePoint];
    {$ifdef MSWINDOWS}
    Rec1.FileExtension := ExeVersion.ProgramFileName;
    {$endif}
    Rec2.ID := i1;
    Rec2.TimeStamp64 := c;
    Rec2.JSON := 'abc';
    RecRes := I.ComplexCall(Ints,Strs1,Str2,Rec1,Rec2,n1,n2);
    Check(length(Str2)=4);
    Check(Str2[0]='ABC');
    Check(Str2[1]='DEF');
    Check(Str2[2]='GHIJK');
    Check(Str2[3]='one,two,three');
    Check(Rec1.Features=[vtTransaction,vtSavePoint]);
    {$ifdef MSWINDOWS}
    Check(Rec1.FileExtension=ExeVersion.ProgramFileName);
    {$endif}
    Check(Rec2.ID=i1+1);
    Check(Rec2.TimeStamp64=c-1);
    Check(Rec2.JSON=IntegerDynArrayToCSV(Ints,length(Ints)));
    Check(RecRes.ID=i1);
    Check(RecRes.TimeStamp64=c);
    Check(RecRes.JSON=StringToUTF8(Rec1.FileExtension));
    CheckSame(n1,n2);






|







 







|







 







<




<







 







<
<







 







<
<







 







<






|
|







 







<







 







<






<







 







|




|



>







 







|







 







|
|








>
|







 







|







 







|







 







|







 







|







 







>
|







 







<

<










<

<







389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
....
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
....
4022
4023
4024
4025
4026
4027
4028

4029
4030
4031
4032

4033
4034
4035
4036
4037
4038
4039
....
4088
4089
4090
4091
4092
4093
4094


4095
4096
4097
4098
4099
4100
4101
....
4113
4114
4115
4116
4117
4118
4119


4120
4121
4122
4123
4124
4125
4126
....
4426
4427
4428
4429
4430
4431
4432

4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
....
4462
4463
4464
4465
4466
4467
4468

4469
4470
4471
4472
4473
4474
4475
....
5152
5153
5154
5155
5156
5157
5158

5159
5160
5161
5162
5163
5164

5165
5166
5167
5168
5169
5170
5171
....
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
....
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
....
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
....
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
....
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
....
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
....
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
.....
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
.....
11051
11052
11053
11054
11055
11056
11057

11058

11059
11060
11061
11062
11063
11064
11065
11066
11067
11068

11069

11070
11071
11072
11073
11074
11075
11076
    /// release used instances and memory
    procedure CleanUp; override;
  published
    /// direct LZ77 deflate/inflate functions
    procedure InMemoryCompression;
    /// .gzip archive handling
    procedure GZIPFormat;
    {$ifndef LINUX}
    /// .zip archive handling
    procedure ZIPFormat;
    {$endif}
    /// SynLZO internal format
    procedure _SynLZO;
    /// SynLZ internal format
    procedure _SynLZ;
................................................................................
    Check(T.AddField('bool',tftBoolean)=nil);
    Check(T.AddField('double',tftDouble)<>nil);
    Check(T.AddField('varint',tftVarUInt32)<>nil);
    Check(T.AddField('text',tftUTF8,[tfoUnique])<>nil);
    Check(T.AddField('ansi',tftWinAnsi,[])<>nil);
    Check(T.AddField('currency',tftCurrency)<>nil);
    Test;
    FN := ChangeFileExt(ExeVersion.ProgramFileName,'.syntable');
    DeleteFile(FN);
    W := TFileBufferWriter.Create(FN); // manual storage of TSynTable header
    try
      T.SaveTo(W);
      W.Flush;
    finally
      W.Free;
................................................................................
    fFileVersions: TFVs;
    class function FVReader(P: PUTF8Char; var aValue;
      out aValid: Boolean): PUTF8Char;
    class procedure FVWriter(const aWriter: TTextWriter; const aValue);
    class function FVReader2(P: PUTF8Char; var aValue;
      out aValid: Boolean): PUTF8Char;
    class procedure FVWriter2(const aWriter: TTextWriter; const aValue);

    class function FVClassReader(const aValue: TObject; aFrom: PUTF8Char;
      var aValid: Boolean; aOptions: TJSONToObjectOptions): PUTF8Char;
    class procedure FVClassWriter(const aSerializer: TJSONSerializer;
      aValue: TObject; aOptions: TTextWriterWriteObjectOptions);

  published
    property Ints: TIntegerDynArray read fInts write fInts;
    property TimeLog: TTimeLogDynArray read fTimeLog write fTimeLog;
    property FileVersion: TFVs read fFileVersions write fFileVersions;
  end;


................................................................................
class procedure TCollTstDynArray.FVWriter2(const aWriter: TTextWriter; const aValue);
var V: TFV absolute aValue;
begin
  aWriter.AddJSONEscape(['Major',V.Major,'Minor',V.Minor,'Release',V.Release,
    'Build',V.Build,'Main',V.Main,'Detailed',V.Detailed]);
end;



class function TCollTstDynArray.FVClassReader(const aValue: TObject; aFrom: PUTF8Char;
  var aValid: Boolean; aOptions: TJSONToObjectOptions): PUTF8Char;
var V: TFileVersion absolute aValue;
    Values: TPUtf8CharDynArray;
begin // '{"Major":2,"Minor":2002,"Release":3002,"Build":4002,"Main":"2","BuildDateTime":"1911-03-15"}'
  result := JSONDecode(aFrom,['Major','Minor','Release','Build','Main','BuildDateTime'],Values);
  aValid := (result<>nil);
................................................................................
  aValue: TObject; aOptions: TTextWriterWriteObjectOptions);
var V: TFileVersion absolute aValue;
begin
  aSerializer.AddJSONEscape(['Major',V.Major,'Minor',V.Minor,'Release',V.Release,
    'Build',V.Build,'Main',V.Main,'BuildDateTime',DateTimeToIso8601Text(V.BuildDateTime)]);
end;




{ TCollTests }

function TCollTests.Add: TCollTest;
begin
  result := inherited Add as TCollTest;
end;
................................................................................
      Check(Main=IntToStr(i));
      Check(Detailed=IntToStr(i+1000));
    end;
  finally
    CA.Free;
  end;
end;

procedure TFileVersionTest(Full: boolean);
var V,F: TFileVersion;
    J: RawUTF8;
    i: integer;
    Valid: boolean;
begin
  V := TFileVersion.Create('',0,0,0);
  F := TFileVersion.Create('',0,0,0);
  try
    for i := 1 to 1000 do begin
      if Full then begin
        V.Major := i;
        V.Minor := i+2000;
        V.Release := i+3000;
        V.Build := i+4000;
................................................................................
      CheckSame(V.BuildDateTime,F.BuildDateTime);
    end;
  finally
    F.Free;
    V.Free;
  end;
end;

{$endif}
{$endif}
procedure ABCD;
begin
  Check(Parser.Root.NestedProperty[0].PropertyName='A');
  Check(Parser.Root.NestedProperty[0].PropertyType=ptInteger);
  Check(Parser.Root.NestedProperty[1].PropertyName='B');
................................................................................
  TTextWriter.RegisterCustomJSONSerializer(TypeInfo(TFVs),
    TCollTstDynArray.FVReader,TCollTstDynArray.FVWriter);
  TCollTstDynArrayTest;
  TTextWriter.RegisterCustomJSONSerializer(TypeInfo(TFVs),
    TCollTstDynArray.FVReader2,TCollTstDynArray.FVWriter2);
  TCollTstDynArrayTest;
  // (custom) class serialization

  TFileVersionTest(false);
  TJSONSerializer.RegisterCustomSerializer(TFileVersion,
    TCollTstDynArray.FVClassReader,TCollTstDynArray.FVClassWriter);
  TFileVersionTest(true);
  TJSONSerializer.RegisterCustomSerializer(TFileVersion,nil,nil);
  TFileVersionTest(false);

{$endif DELPHI5OROLDER}
{$endif LVCL}
  // test TJSONRecordTextDefinition parsing
  Parser := TJSONRecordTextDefinition.FromCache(nil,'Int: double');
  Check(Length(Parser.Root.NestedProperty)=1);
  Check(Parser.Root.NestedProperty[0].PropertyName='Int');
  Check(Parser.Root.NestedProperty[0].PropertyType=ptDouble);
................................................................................
var comp: Integer;
    tmp: RawByteString;
begin
  Check(CRC32string('TestCRC32')=$2CB8CDF3);
  tmp := RawByteString(Ident);
  for comp := 0 to 9 do
    Check(UnCompressString(CompressString(tmp,False,comp))=tmp);
  Data := StringFromFile(ExeVersion.ProgramFileName);
  Check(UnCompressString(CompressString(Data,False,6))=Data);
end;


{$ifndef LINUX} // TZipRead not defined yet (use low-level file mapping WinAPI)

procedure TTestCompression.ZipFormat;
var FN: TFileName;
    ExeName: string;
    S: TRawByteStringStream;
procedure Test(Z: TZipRead; aCount: integer);
var i: integer;
    tmp: RawByteString;
    crc: Cardinal;
begin
  with Z do
................................................................................
    i := NameToIndex('REp2\ident.gz');
    Check(i=1);
    crc := crc32(0,M.Memory,M.Position);
    Check(Entry[i].infoLocal^.zcrc32=crc);
    tmp := UnZip(i);
    Check(tmp<>'');
    Check(crc32(0,pointer(tmp),length(tmp))=crc);
    i := NameToIndex(ExeName);
    Check(i=2);
    Check(UnZip(i)=Data);
    Check(Entry[i].infoLocal^.zcrc32=crc32(0,pointer(Data),length(Data)));
    i := NameToIndex('REp2\ident2.gz');
    Check(i=3);
    Check(Entry[i].infoLocal^.zcrc32=crc);
    tmp := UnZip(i);
................................................................................
  with Z do
  try
    AddDeflated('rep1\one.exe',pointer(Data),length(Data));
    Check(Count=1);
    AddDeflated('rep2\ident.gz',M.Memory,M.Position);
    Check(Count=2);
    if Z is TZipWrite then
      TZipWrite(Z).AddDeflated(ExeVersion.ProgramFileName) else
      Z.AddDeflated(ExeName,pointer(Data),length(Data));
    Check(Count=3,'direct zip file');
    AddStored('rep2\ident2.gz',M.Memory,M.Position);
    Check(Count=4);
  finally
    Free;
  end;
end;
begin
  ExeName := ExtractFileName(ExeVersion.ProgramFileName);
  FN := ChangeFileExt(ExeVersion.ProgramFileName,'.zip');
  Prepare(TZipWrite.Create(FN));
  Test(TZipRead.Create(FN),4);
  S := TRawByteStringStream.Create;
  try
    Prepare(TZipWriteToStream.Create(S));
    Test(TZipRead.Create(pointer(S.DataString),length(S.DataString)),4);
  finally
................................................................................
  finally
    Free;
  end;
  Test(TZipRead.Create(FN),5);
  DeleteFile(FN);
end;

{$endif LINUX}

procedure TTestCompression._SynLZO;
var s,t: AnsiString;
    i: integer;
begin
  for i := 0 to 1000 do begin
    t := RandomString(i*8);
................................................................................
  Value[10] := #$E9;
  Value[16] := #$E7;
  Value[17] := #$E0;
  Check(not IsBase64(Value));
  Check(Base64Encode(Value)=Value64);
  Check(BinToBase64(Value)=Value64);
  Check(IsBase64(Value64));
  tmp := StringFromFile(ExeVersion.ProgramFileName);
  b64 := Base64Encode(tmp);
  Check(IsBase64(b64));
  Check(Base64Decode(b64)=tmp);
  Check(BinToBase64(tmp)=b64);
  Check(Base64ToBin(b64)=tmp);
  tmp := '';
  for i := 1 to 1998 do begin
................................................................................
        WS := 'Texte accentue n.'+IntToString(i);
        PWordArray(WS)^[13] := 233;
        PWordArray(WS)^[16] := 176;
        Canvas.TextOutW(100,y,pointer(WS));
        dec(y,9+i);
      end;
      SaveToStream(MS,FIXED_DATE);
      //MS.SaveToFile(ChangeFileExt(ExeVersion.ProgramFileName,'.pdf'));
      Check(Hash32(MS.Memory,MS.Position)=Hash[embed]);
      if not embed then begin
        if CharSet<>ANSI_CHARSET then
          break; // StandardFontsReplace will work only with ANSI code page
        NewDoc;
        MS.Clear;
      end;
................................................................................
      finally
        MF.Free;
      end;
      MS.Clear;
      SaveToStream(MS,FIXED_DATE);
      // force constant Arial,Bold and Tahoma FontBBox
      SetString(s,PAnsiChar(MS.Memory),MS.Position);
      MS.SaveToFile(ChangeFileExt(ExeVersion.ProgramFileName,'.pdf'));
      if (GetACP<>1252) {$ifdef CPU64}or true{$endif} then
        Check(length(s)>6500) else begin
        i := PosEx('/FontBBox[',s);
        if CheckFailed(i=5580) then exit;
        fillchar(s[i],32,32);
        j := PosEx('/FontBBox[',s);
        if CheckFailed(j=5910) then exit;
................................................................................


{ TServicePerThread }

constructor TServicePerThread.Create;
begin
  inherited;
  fThreadIDAtCreation :=
    {$ifdef MSWINDOWS}Windows.{$else}SynCommons.{$endif}GetCurrentThreadID;
end;

function TServicePerThread.GetCurrentThreadID: cardinal;
begin
  result := {$ifdef MSWINDOWS}Windows.{$else}SynCommons.{$endif}GetCurrentThreadID;
  with PServiceRunningContext(@ServiceContext)^ do
    if Request<>nil then
................................................................................
    Ints[1] := i2;
    SetLength(Str2,3);
    Str2[0] := 'ABC';
    Str2[1] := 'DEF';
    Str2[2] := 'GHIJK';
    fillchar(Rec1,sizeof(Rec1),0);
    Rec1.Features := [vtTransaction,vtSavePoint];

    Rec1.FileExtension := ExeVersion.ProgramFileName;

    Rec2.ID := i1;
    Rec2.TimeStamp64 := c;
    Rec2.JSON := 'abc';
    RecRes := I.ComplexCall(Ints,Strs1,Str2,Rec1,Rec2,n1,n2);
    Check(length(Str2)=4);
    Check(Str2[0]='ABC');
    Check(Str2[1]='DEF');
    Check(Str2[2]='GHIJK');
    Check(Str2[3]='one,two,three');
    Check(Rec1.Features=[vtTransaction,vtSavePoint]);

    Check(Rec1.FileExtension=ExeVersion.ProgramFileName);

    Check(Rec2.ID=i1+1);
    Check(Rec2.TimeStamp64=c-1);
    Check(Rec2.JSON=IntegerDynArrayToCSV(Ints,length(Ints)));
    Check(RecRes.ID=i1);
    Check(RecRes.TimeStamp64=c);
    Check(RecRes.JSON=StringToUTF8(Rec1.FileExtension));
    CheckSame(n1,n2);

Changes to SynTests.pas.

907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
...
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    C: TSynTestCase;
    ILog: IUnknown;
begin
  if TTextRec(fSaveToFile).Handle=0 then
    CreateSaveToFile;
  Color(ccLightCyan);
  Writeln(fSaveToFile,#13#10'   ',Ident,#13#10'  ',StringOfChar('-',length(Ident)+2));
{$ifdef MSWINDOWS}
  RunTimer.Start;
  ExeVersionRetrieve;
{$endif}
  C := nil;
  try
    // 1. register all test cases
    fTestCase.Clear;
    for m := 0 to Count-1 do begin
      C := pointer(m);
      fCurrentMethod := m;
................................................................................
      fFailed.AddObject(E.ClassName+': '+E.Message,C);
      writeln(fSaveToFile,#13#10'! Exception ',E.ClassName,
        ' raised with messsage:'#13#10'!  ',E.Message);
    end;
  end;
  Color(ccLightCyan);
  result := (fFailed.Count=0);
{$ifdef MSWINDOWS}
  Elapsed := #13#10#13#10'Time elapsed for all tests: '+RunTimer.Stop;
  if Exeversion.Version.Major<>0 then
    Version := #13#10'Software version tested: '+RawUTF8(Exeversion.Version.Detailed);
{$endif}
  Writeln(fSaveToFile,#13#10,Version,CustomVersions,
    #13#10'Generated with: ',GetDelphiCompilerVersion,' compiler', Elapsed,
    #13#10'Tests performed at ',DateTimeToStr(Now));
  if result then
    Color(ccWhite) else
    Color(ccLightRed);
  write(fSaveToFile,#13#10'Total assertions failed for all test suits:  ',






<

<
<







 







<



<







907
908
909
910
911
912
913

914


915
916
917
918
919
920
921
...
964
965
966
967
968
969
970

971
972
973

974
975
976
977
978
979
980
    C: TSynTestCase;
    ILog: IUnknown;
begin
  if TTextRec(fSaveToFile).Handle=0 then
    CreateSaveToFile;
  Color(ccLightCyan);
  Writeln(fSaveToFile,#13#10'   ',Ident,#13#10'  ',StringOfChar('-',length(Ident)+2));

  RunTimer.Start;


  C := nil;
  try
    // 1. register all test cases
    fTestCase.Clear;
    for m := 0 to Count-1 do begin
      C := pointer(m);
      fCurrentMethod := m;
................................................................................
      fFailed.AddObject(E.ClassName+': '+E.Message,C);
      writeln(fSaveToFile,#13#10'! Exception ',E.ClassName,
        ' raised with messsage:'#13#10'!  ',E.Message);
    end;
  end;
  Color(ccLightCyan);
  result := (fFailed.Count=0);

  Elapsed := #13#10#13#10'Time elapsed for all tests: '+RunTimer.Stop;
  if Exeversion.Version.Major<>0 then
    Version := #13#10'Software version tested: '+RawUTF8(Exeversion.Version.Detailed);

  Writeln(fSaveToFile,#13#10,Version,CustomVersions,
    #13#10'Generated with: ',GetDelphiCompilerVersion,' compiler', Elapsed,
    #13#10'Tests performed at ',DateTimeToStr(Now));
  if result then
    Color(ccWhite) else
    Color(ccLightRed);
  write(fSaveToFile,#13#10'Total assertions failed for all test suits:  ',

Changes to SynopseCommit.inc.

1
'1.18.901'
|
1
'1.18.902'