-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
test.orm.sqlite3.pas
2826 lines (2722 loc) · 100 KB
/
test.orm.sqlite3.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// regression tests for ORM on the SQlite3 engine over Http or WebSockets
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit test.orm.sqlite3;
interface
{$I ..\src\mormot.defines.inc}
{.$undef ORMGENERICS}
uses
sysutils,
contnrs,
classes,
{$ifndef FPC}
typinfo, // to avoid Delphi inlining problems
{$endif FPC}
mormot.core.base,
mormot.core.os,
mormot.core.text,
mormot.core.buffers,
mormot.core.unicode,
mormot.core.datetime,
mormot.core.rtti,
{$ifdef ORMGENERICS} // not supported on oldest compilers (e.g. < Delphi XE8)
mormot.core.collections,
{$endif ORMGENERICS}
mormot.crypt.core,
mormot.core.data,
mormot.core.variants,
mormot.core.json,
mormot.core.log,
mormot.core.perf,
mormot.core.search,
mormot.core.mustache,
mormot.core.test,
mormot.core.interfaces,
mormot.crypt.jwt,
mormot.net.client,
mormot.net.server,
mormot.net.relay,
mormot.net.ws.core,
mormot.net.ws.client,
mormot.net.ws.server,
mormot.db.core,
mormot.db.nosql.bson,
mormot.orm.base,
mormot.orm.core,
mormot.orm.rest,
mormot.orm.storage,
mormot.orm.sqlite3,
mormot.orm.client,
mormot.orm.server,
mormot.soa.core,
mormot.soa.server,
mormot.rest.core,
mormot.rest.client,
mormot.rest.server,
mormot.rest.memserver,
mormot.rest.sqlite3,
mormot.rest.http.client,
mormot.rest.http.server,
mormot.db.raw.sqlite3,
mormot.db.raw.sqlite3.static,
test.core.data,
test.core.base,
test.orm.core;
type
/// a parent test case which will test most functions, classes and types defined
// and implemented in the mormot.db.raw.sqlite3 unit, i.e. the SQLite3 engine
// - it should not be called directly, but through TTestSqliteFile,
// TTestSqliteMemory and TTestSqliteMemory children
TTestSQLite3Engine = class(TSynTestCase)
protected
{ these values are used internally by the published methods below }
BackupProgressStep: TOnSqlDatabaseBackupStep; // should be the first
TempFileName: TFileName;
EncryptedFile: boolean;
Demo: TSqlDataBase;
Req: RawUtf8;
JS, JSExp: RawUtf8;
DV: variant;
BackupTimer: TPrecisionTimer;
function OnBackupProgress(Sender: TSqlDatabaseBackupThread): boolean;
published
/// test direct access to the SQLite3 engine
// - i.e. via TSqlDataBase and TSqlRequest classes
procedure DatabaseDirectAccess;
/// test direct access to the Virtual Table features of SQLite3
procedure VirtualTableDirectAccess;
/// test the TOrmTableJson table
// - the JSON content generated must match the original data
// - a VACCUM is performed, for testing some low-level SQLite3 engine
// implementation
// - the SortField feature is also tested
procedure _TOrmTableJson;
/// test the TRestClientDB, i.e. a local Client/Server driven usage
// of the framework
// - validates TOrmModel, TRestServer and TRestStorage by checking
// the coherency of the data between client and server instances, after
// update from both sides
// - use all RESTful commands (GET/UDPATE/POST/DELETE...)
// - test the 'many to many' features (i.e. TOrmMany) and dynamic
// arrays published properties handling
// - test dynamic tables
procedure _TRestClientDB;
{$ifndef NOSQLITE3STATIC}
/// check SQlite3 internal regex.c function
procedure RegexpFunction;
{$endif NOSQLITE3STATIC}
/// test Master/Slave replication using TRecordVersion field
procedure _TRecordVersion;
end;
/// this test case will test most functions, classes and types defined and
// and implemented in the mormot.db.raw.sqlite3 unit, i.e. the SQLite3 engine
// with a file-based approach
TTestSqliteFile = class(TTestSQLite3Engine);
/// this test case will test most functions, classes and types defined and
// and implemented in the mormot.db.raw.sqlite3 unit, i.e. the SQLite3 engine
// with a file-based approach
// - purpose of this class is to test Write-Ahead Logging for the database
TTestSqliteFileWAL = class(TTestSqliteFile);
/// this test case will test most functions, classes and types defined and
// and implemented in the mormot.db.raw.sqlite3 unit, i.e. the SQLite3 engine
// with a file-based approach
// - purpose of this class is to test Memory-Mapped I/O for the database
TTestSqliteFileMemoryMap = class(TTestSqliteFile);
/// this test case will test most functions, classes and types defined and
// and implemented in the mormot.db.raw.sqlite3 unit, i.e. the SQLite3 engine
// with a memory-based approach
// - this class will also test the TRestStorage class, and its
// 100% Delphi simple database engine
TTestSqliteMemory = class(TTestSQLite3Engine)
protected
function CreateShardDB(maxshard: Integer): TRestServer;
published
/// test the TOrmTableWritable table
procedure _TOrmTableWritable;
/// validate RTREE virtual tables
procedure _RTree;
/// validate TRestStorageShardDB add operation, with or without batch
procedure ShardWrite;
/// validate TRestStorageShardDB reading among all sharded databases
procedure ShardRead;
/// validate TRestStorageShardDB reading after deletion of several shards
procedure ShardReadAfterPurge;
/// validate TRestStorageShardDB.MaxShardCount implementation
procedure _MaxShardCount;
end;
/// this class defined two published methods of type TRestServerCallBack in
// order to test the Server-Side ModelRoot/TableName/ID/MethodName RESTful model
TRestServerTest = class(TRestServerDB)
published
/// test ModelRoot/People/ID/DataAsHex
// - this method is called by TRestServer.Uri when a
// ModelRoot/People/ID/DataAsHex GET request is provided
// - Parameters values are not used here: this service only need aRecord.ID
// - SentData is set with incoming data from a PUT method
// - if called from ModelRoot/People/ID/DataAsHex with GET or PUT methods,
// TRestServer.Uri will create a TOrm instance and set its ID
// (but won't retrieve its other field values automaticaly)
// - if called from ModelRoot/People/DataAsHex with GET or PUT methods,
// TRestServer.Uri will leave aRecord.ID=0 before launching it
// - if called from ModelRoot/DataAsHex with GET or PUT methods,
// TRestServer.Uri will leave aRecord=nil before launching it
// - implementation must return the HTTP error code (e.g. 200 as success)
// - Table is overloaded as TOrmPeople here, and still match the
// TRestServerCallBack prototype: but you have to check the class
// at runtime: it can be called by another similar but invalid URL, like
// ModelRoot/OtherTableName/ID/DataAsHex
procedure DataAsHex(Ctxt: TRestServerUriContext);
/// method used to test the Server-Side ModelRoot/Sum or
// ModelRoot/People/Sum Requests with JSON process
// - _GET_ prefix will force that only mGET is allowed
// - implementation of this method returns the sum of two floating-points,
// named A and B, as in the public TOrmPeople.Sum() method,
// which implements the Client-Side of this service
// - Table nor ID are never used here
procedure _GET_Sum(Ctxt: TRestServerUriContext);
/// method used to test the Server-Side ModelRoot/Sum or
// ModelRoot/People/Sum Requests with variant process
// - _GET__POST_ prefix will force that only mGET and mPOST are allowed
procedure _GET__POST_Sum2(Ctxt: TRestServerUriContext);
end;
type
TOrmASource = class;
TOrmADest = class;
TOrmADests = class(TOrmMany)
private
fTime: TDateTime;
fDest: TOrmADest;
fSource: TOrmASource;
published
property Source: TOrmASource
read fSource;
property Dest: TOrmADest
read fDest;
property AssociationTime: TDateTime
read fTime write fTime;
end;
TOrmASource = class(TOrmSigned)
private
fDestList: TOrmADests;
published
property SignatureTime;
property Signature;
property DestList: TOrmADests
read fDestList;
end;
TOrmADest = class(TOrmSigned)
published
property SignatureTime;
property Signature;
end;
procedure TestMasterSlaveRecordVersion(Test: TSynTestCase; const DBExt: TFileName);
procedure InternalTestMany(Test: TSynTestCase; aClient: TRestOrmClientUri);
implementation
uses
test.soa.network;
{ TTestSQLite3Engine }
function TTestSQLite3Engine.OnBackupProgress(Sender: TSqlDatabaseBackupThread): boolean;
begin
BackupProgressStep := Sender.Step;
result := true;
end;
procedure InternalSQLFunctionCharIndex(Context: TSqlite3FunctionContext;
argc: integer; var argv: TSqlite3ValueArray); cdecl;
var
StartPos: integer;
begin
case argc of
2:
StartPos := 1;
3:
begin
StartPos := sqlite3.value_int64(argv[2]);
if StartPos <= 0 then
StartPos := 1;
end;
else
begin
ErrorWrongNumberOfArgs(Context, 'charindex');
exit;
end;
end;
if (sqlite3.value_type(argv[0]) = SQLITE_NULL) or
(sqlite3.value_type(argv[1]) = SQLITE_NULL) then
sqlite3.result_int64(Context, 0)
else
sqlite3.result_int64(Context,
PosEx(sqlite3.value_text(argv[0]), sqlite3.value_text(argv[1]), StartPos));
end;
const
// BLOBs are stored as array of byte to avoid any charset/IDE conflict
BlobDali: array[0..3] of byte = (
97, 233, 224, 231);
BlobMonet: array[0..13] of byte = (
224, 233, 231, ord('d'), ord('s'), ord('j'), ord('d'), ord('s'),
ord('B'), ord('L'), ord('O'), ord('B'), ord('2'), ord('3'));
// some WinAnsi chars to avoid any charset/IDE conflict
UTF8_E0_F4_BYTES: array[0..5] of byte = (
$E0, $E7, $E8, $E9, $EA, $F4);
var
// manual encoding of some UTF-8 chars to avoid any charset/IDE conflict
_uE0, _uE7, _uE8, _uE9, _uEA, _uF4: RawUtf8;
procedure TTestSQLite3Engine.DatabaseDirectAccess;
procedure InsertData(n: integer);
var
i: integer;
s, ins: RawUtf8;
R: TSqlRequest;
begin
// this is a lot faster than sqlite3 itself, even if it use Utf-8 encoding:
// -> we test the engine speed, not the test routines speed :)
ins :=
'INSERT INTO People (FirstName,LastName,Data,YearOfBirth,YearOfDeath) VALUES (''';
for i := 1 to n do
begin
UInt32ToUtf8(i, s);
// we put some accents in order to test UTF-8 encoding
R.Prepare(Demo.DB, ins + 'Salvador' + s + ''', ''Dali'', ?, 1904, 1989);');
R.Bind(1, @BlobDali, 4); // Bind Blob
R.Execute;
Demo.Execute(ins + 'Samuel Finley Breese' + s + ''', ''Morse'', ''a' +
_uE9 + _uE0 + _uE7 + ''', 1791, 1872);');
Demo.Execute(ins + 'Sergei' + s + ''', ''Rachmaninoff'', ''' + _uE9 + 'z' +
_uE7 + 'b'', 1873, 1943);');
Demo.Execute(ins + 'Alexandre' + s + ''', ''Dumas'', ''' + _uE9 + _uE7 +
'b'', 1802, 1870);');
Demo.Execute(ins + 'Franz' + s + ''', ''Schubert'', ''' + _uE9 + _uE0 +
_uE7 + 'a'', 1797, 1828);');
Demo.Execute(ins + 'Leonardo' + s + ''', ''da Vin' + _uE7 + 'i'', ''@' +
_uE7 + 'b'', 1452, 1519);');
Demo.Execute(ins + 'Aldous Leonard' + s + ''', ''Huxley'', ''' + _uE9 +
_uE0 + ''', 1894, 1963);');
R.Prepare(Demo.DB, ins + 'Claud' + _uE8 + s + #10#7''', ''M' + _uF4 +
'net'', ?, 1840, 1926);');
R.Bind(1, @BlobMonet, sizeof(BlobMonet)); // Bind Blob
R.Execute;
R.Prepare(Demo.DB,
'INSERT INTO People (FirstName,LastName,Data,YearOfBirth,YearOfDeath)' +
' VALUES (?,?,?,?,?)');
R.BindS(1, string('Albert' + s));
R.BindS(2, 'Einstein');
R.Bind(3, _uE9 + _uE7 + 'p');
R.Bind(4, 1879);
R.Bind(5, 1955);
R.Execute;
// Demo.Execute(ins+'Albert'+s+''', ''Einstein'', '''+_uE9+_uE7+'p'', 1879, 1955);');
Demo.Execute(ins + 'Johannes' + s + ''', ''Gutenberg'', ''' + _uEA +
'mls'', 1400, 1468);');
Demo.Execute(ins + 'Jane' + s + ''', ''Aust' + _uE8 + 'n'', ''' + _uE7 +
_uE0 + _uE7 + 'm'', 1775, 1817);');
end;
end;
var
SoundexValues: array[0..5] of RawUtf8;
Names: TRawUtf8DynArray;
i, i1, i2: integer;
Res: Int64;
id: TID;
password, s, s2: RawUtf8;
R: TSqlRequest;
begin
check(JsonGetID('{"id":123}', id) and
(id = 123));
check(JsonGetID('{"rowid":1234}', id) and
(id = 1234));
check(JsonGetID(' { "id": 123}', id) and
(id = 123));
check(JsonGetID(' { "ROWID": 1234}', id) and
(id = 1234));
check(JsonGetID('{id:123}', id) and
(id = 123));
check(JsonGetID('{rowid:1234}', id) and
(id = 1234));
check(not JsonGetID('{"id":0}', id));
check(not JsonGetID('{"id":-10}', id));
check(not JsonGetID('{"id":null}', id));
check(not JsonGetID('{"ROWID":null}', id));
check(not JsonGetID('{id:0}', id));
check(not JsonGetID('{id:-10}', id));
check(not JsonGetID('{"ide":123}', id));
check(not JsonGetID('{"rowide":1234}', id));
check(not JsonGetID('{"as":123}', id));
check(not JsonGetID('{"s":1234}', id));
check(not JsonGetID('"ide":123}', id));
check(not JsonGetID('{ "rowide":1234}', id));
if ClassType = TTestSqliteMemory then
TempFileName := SQLITE_MEMORY_DATABASE_NAME
else
begin
TempFileName := WorkDir + 'test.db3';
DeleteFile(TempFileName); // use a temporary file
{$ifndef NOSQLITE3STATIC}
if ClassType <> TTestSqliteFileMemoryMap then
// memory map is not compatible with our encryption
password := 'password1';
{$endif NOSQLITE3STATIC}
end;
EncryptedFile := ({%H-}password <> '');
Demo := TSqlDataBase.Create(TempFileName, password);
Demo.Synchronous := smOff;
Demo.LockingMode := lmExclusive;
if ClassType = TTestSqliteFileMemoryMap then
Demo.MemoryMappedMB := 256; // will do nothing for SQLite3 < 3.7.17
R.Prepare(Demo.DB, 'select mod(?,?)');
for i1 := 0 to 100 do
for i2 := 1 to 100 do
begin
R.Bind(1, i1);
R.Bind(2, i2);
check(R.Step = SQLITE_ROW);
check(R.FieldInt(0) = i1 mod i2);
R.Reset;
end;
R.Bind([12037, 239]);
check(R.Step = SQLITE_ROW);
check(R.FieldInt(0) = 12037 mod 239);
R.Close;
SoundexValues[0] := 'bonjour';
SoundexValues[1] := 'bonchour';
SoundexValues[2] := 'Bnjr';
SoundexValues[3] := 'mohammad';
SoundexValues[4] := 'mohhhammeeet';
SoundexValues[5] := 'bonjourtr' + _uE8 + 'slongmotquid' + _uE9 + 'passe';
for i1 := 0 to high(SoundexValues) do
begin
s := FormatUtf8('SELECT SoundEx("%");', [SoundexValues[i1]]);
Demo.Execute(s, Res);
CheckEqual(Res, SoundExUtf8(pointer(SoundexValues[i1])), s);
s := FormatUtf8('SELECT UnicodeUpper("%");', [SoundexValues[i1]]);
Demo.Execute(s, s2);
CheckEqual(s2, UpperCaseReference(SoundexValues[i1]), s);
end;
for i1 := 0 to high(SoundexValues) do
begin
s := FormatUtf8('SELECT SoundExFr("%");', [SoundexValues[i1]]);
Demo.Execute(s, Res);
CheckUtf8(Res = SoundExUtf8(pointer(SoundexValues[i1]), nil, sndxFrench), s);
end;
for i1 := 0 to high(SoundexValues) do
begin
s := FormatUtf8('SELECT SoundExEs("%");', [SoundexValues[i1]]);
Demo.Execute(s, Res);
CheckUtf8(Res = SoundExUtf8(pointer(SoundexValues[i1]), nil, sndxSpanish), s);
end;
Demo.RegisterSQLFunction(InternalSQLFunctionCharIndex, 2, 'CharIndex');
Demo.RegisterSQLFunction(InternalSQLFunctionCharIndex, 3, 'CharIndex');
for i1 := 0 to high(SoundexValues) do
begin
s := FormatUtf8('SELECT CharIndex("o","%");', [SoundexValues[i1]]);
Demo.Execute(s, Res);
CheckUtf8(Res = PosEx('o', SoundexValues[i1]), s);
s := FormatUtf8('SELECT CharIndex("o","%",5);', [SoundexValues[i1]]);
Demo.Execute(s, Res);
CheckUtf8(Res = PosEx('o', SoundexValues[i1], 5), s);
end;
Demo.UseCache := true; // use the cache for the JSON requests
Demo.WALMode := InheritsFrom(TTestSqliteFileWAL); // test Write-Ahead Logging
check(Demo.WALMode = InheritsFrom(TTestSqliteFileWAL));
Demo.Execute(' CREATE TABLE IF NOT EXISTS People (' +
' ID INTEGER PRIMARY KEY,' + ' FirstName TEXT COLLATE SYSTEMNOCASE,' +
' LastName TEXT,' + ' Data BLOB,' + ' YearOfBirth INTEGER,' +
' YearOfDeath INTEGER); ');
// Inserting data 1x without transaction ');
InsertData(1);
{ Insert some sample data - now with transaction. Multiple records are
inserted and not yet committed until the transaction is finally ended.
This single transaction is very fast compared to multiple individual
transactions. It is even faster than other database engines. }
Demo.TransactionBegin;
InsertData(1000);
Demo.Commit;
Req := 'SELECT * FROM People WHERE LastName=''M' + _uF4 + 'net'' ORDER BY FirstName;';
check(WinAnsiToUtf8(Utf8ToWinAnsi(Req)) = Req, 'WinAnsiToUtf8/Utf8ToWinAnsi');
JSExp := Demo.ExecuteJson(Req, {expand=}true);
Demo.CacheFlush;
JS := Demo.ExecuteJson(Req, {expand=}false); // get result in JSON format
FileFromString(JS, WorkDir + 'Test1.json');
CheckHash(JS, $40C1649A, 'ExecuteJson');
R.Prepare(Demo.DB, 'SELECT * FROM People WHERE LastName=? ORDER BY FirstName');
R.Bind([RawUtf8('M' + _uF4 + 'net')]);
R.ExecuteDocVariant(Demo.DB, '', DV);
R.Close;
CheckEqual(_Safe(DV).Count, 1001);
JS := _Safe(DV).ToNonExpandedJson;
FileFromString(JS, WorkDir + 'Test2.json');
CheckHash(JS, $93E54870, 'ExecuteDocVariant');
{$ifndef NOSQLITE3STATIC}
if password <> '' then
begin
// check file encryption password change
check(Demo.MemoryMappedMB = 0, 'mmap pragma disallowed');
FreeAndNil(Demo); // if any exception occurs in Create(), Demo.Free is OK
check(IsSQLite3File(TempFileName));
check(IsSQLite3FileEncrypted(TempFileName));
check(not IsOldSqlEncryptTable(TempFileName));
check(not ChangeSqlEncryptTablePassWord(TempFileName, 'password1', 'password1'));
check(IsSQLite3File(TempFileName));
check(IsSQLite3FileEncrypted(TempFileName));
check(not IsOldSqlEncryptTable(TempFileName));
check(ChangeSqlEncryptTablePassWord(TempFileName, 'password1', ''));
check(IsSQLite3File(TempFileName));
check(not IsOldSqlEncryptTable(TempFileName));
check(not IsSQLite3FileEncrypted(TempFileName));
check(ChangeSqlEncryptTablePassWord(TempFileName, '', 'NewPass'));
check(IsSQLite3File(TempFileName));
check(IsSQLite3FileEncrypted(TempFileName));
check(not IsOldSqlEncryptTable(TempFileName));
Demo := TSqlDataBase.Create(TempFileName, 'NewPass'); // reuse the temporary file
Demo.Synchronous := smOff;
Demo.LockingMode := lmExclusive;
Demo.UseCache := true; // use the cache for the JSON requests
Demo.WALMode := InheritsFrom(TTestSqliteFileWAL); // test Write-Ahead Logging
check(Demo.WALMode = InheritsFrom(TTestSqliteFileWAL));
check(Demo.MemoryMappedMB = 0, 'mmap pragma disallowed');
CheckHash(Demo.ExecuteJson(Req), $40C1649A, 'ExecuteJson crypted');
check(Demo.MemoryMappedMB = 0, 'mmap pragma disallowed');
end
else
{$endif NOSQLITE3STATIC}
if ClassType = TTestSqliteFileMemoryMap then
begin
// force re-open to test reading
FreeAndNil(Demo);
Demo := TSqlDataBase.Create(TempFileName, password);
Demo.Synchronous := smOff;
Demo.LockingMode := lmExclusive;
Demo.MemoryMappedMB := 256;
Demo.UseCache := true;
end;
Demo.GetTableNames(Names);
check(length(Names) = 1);
check(Names[0] = 'People');
Demo.Execute(
'SELECT Concat(FirstName," and ") FROM People WHERE LastName="Einstein"', s);
CheckHash(s, $68A74D8E, 'Albert1 and Albert1 and Albert2 and Albert3 and ...');
i1 := Demo.Execute(
'SELECT FirstName from People WHERE FirstName like "%eona%"', Names);
check(i1 = 2002, 'like/strcspn');
check(Names[i1] = '');
for i := 0 to i1 - 1 do
check(PosEx('eona', Names[i]) > 0);
s := Demo.ExecuteNoExceptionUtf8('SELECT current_timestamp;');
check(s <> '', 'current_timestamp');
s := Demo.ExecuteNoExceptionUtf8('SELECT datetime(current_timestamp);');
check(s <> '', 'datetime');
s := Demo.ExecuteNoExceptionUtf8('SELECT datetime(current_timestamp,''localtime'');');
check(s <> '', 'localtime');
end;
procedure TTestSQLite3Engine.VirtualTableDirectAccess;
const
LOG1: RawUtf8 =
'D:\Dev\lib\SQLite3\exe\TestSQL3.exe 1.2.3.4 (2011-04-07)'#13#10 +
'Host=MyPC User=MySelf CPU=2*0-15-1027 OS=2.3=5.1.2600 Wow64=0 Freq=3579545'#13#10 +
'TSynLog 1.13 LVCL 2011-04-07 12:04:09'#13#10#13#10 +
'20110407 12040904 debug {"TObjectList(00AF8D00)":["TObjectList(00AF8D20)",' +
'"TObjectList(00AF8D60)","TFileVersion(00ADC0B0)","TDebugFile(00ACC990)"]}';
var
Res: Int64;
s, s2, s3: RawUtf8;
n: PtrInt;
begin
// register the Log virtual table module to this connection
RegisterVirtualTableModule(TOrmVirtualTableLog, Demo);
// test Log virtual table module
FileFromString(LOG1, 'temptest.log');
Demo.Execute('CREATE VIRTUAL TABLE test USING log(temptest.log);');
Demo.Execute('select count(*) from test', Res);
check(Res = 1);
n := 0;
s := Demo.ExecuteJson('select * from test', False, @n);
check(s <> '');
check(n = Res);
s2 := Demo.ExecuteJson('select * from test where rowid=2', False, @n);
check(s2 = '{"fieldCount":3,"values":["DateTime","Level","Content"],"rowCount":0}'#$A);
check(n = 0);
s2 := Demo.ExecuteJson('select * from test where rowid=1', False, @n);
check(s2 <> '');
check(s = s2);
check(n = 1);
n := 0;
s3 := Demo.ExecuteJson('select * from test where level=2', False, @n);
check(n = 1);
check(s3 =
'{"fieldCount":3,"values":["DateTime","Level","Content","2011-04-07T12:04:09.064",' +
'2,"20110407 12040904 debug {\"TObjectList(00AF8D00)\":[\"TObjectList(00AF8D20)\",' +
'\"TObjectList(00AF8D60)\",\"TFileVersion(00ADC0B0)\",\"TDebugFile(00ACC990)\"]}"],' +
'"rowCount":1}'#$A);
s3 := Demo.ExecuteJson('select * from test where level=3', False, @n);
CheckEqual(s3,
'{"fieldCount":3,"values":["DateTime","Level","Content"],"rowCount":0}'#$A);
CheckEqual(n, 0);
end;
{$ifndef NOSQLITE3STATIC}
procedure TTestSQLite3Engine.RegexpFunction;
const
EXPRESSIONS: array[0..2] of RawUtf8 = (
'\bFinley\b', '^Samuel F', '\bFinley\b');
var
Model: TOrmModel;
Client: TRestClientDB;
i, n: integer;
begin
// validate compact https://www.sqlite.org/src/file?name=ext/misc/regexp.c
Model := TOrmModel.Create([TOrmPeople]);
Client := TRestClientDB.Create(Model, nil, 'test.db3', TRestServerDB, false, '');
try
for i := 0 to high(EXPRESSIONS) do
with TOrmPeople.CreateAndFillPrepare(Client.Orm,
'FirstName REGEXP ?', [EXPRESSIONS[i]]) do
try
if not CheckFailed(FillContext <> nil) then
begin
CheckEqual(FillContext.Table.RowCount, 1001);
n := 0;
while FillOne do
begin
CheckEqual(LastName, 'Morse');
check(IdemPChar(pointer(FirstName), 'SAMUEL FINLEY '));
inc(n);
end;
CheckEqual(n, 1001);
end;
Client.Server.DB.CacheFlush; // force compile '\bFinley\b' twice
finally
Free;
end;
finally
Client.Free;
Model.Free;
end;
end;
{$endif NOSQLITE3STATIC}
type
TOrmPeopleVersioned = class(TOrmPeople)
protected
fVersion: TRecordVersion;
published
property Version: TRecordVersion
read fVersion write fVersion;
end;
procedure TestMasterSlaveRecordVersion(Test: TSynTestCase; const DBExt: TFileName);
procedure TestMasterSlave(Master, Slave: TRestServer; SynchronizeFromMaster: TRest);
var
res: TRecordVersion;
Rec1, Rec2: TOrmPeopleVersioned;
begin
if SynchronizeFromMaster <> nil then
res := Slave.Server.RecordVersionSynchronizeSlave(
TOrmPeopleVersioned, SynchronizeFromMaster.Orm, 500)
else
res := Slave.Server.RecordVersionCurrent(TOrmPeopleVersioned);
Test.CheckEqual(res, Master.Server.RecordVersionCurrent(TOrmPeopleVersioned));
Rec1 := TOrmPeopleVersioned.CreateAndFillPrepare(
Master.Orm, 'order by ID', '*');
Rec2 := TOrmPeopleVersioned.CreateAndFillPrepare(
Slave.Orm, 'order by ID', '*');
try
Test.CheckEqual(Rec1.FillTable.RowCount, Rec2.FillTable.RowCount);
while Rec1.FillOne do
begin
Test.check(Rec2.FillOne, 'fill');
Test.check(Rec1.SameRecord(Rec2), 'fields');
Test.CheckEqual(Rec1.Version, Rec2.Version, 'version');
end;
finally
Rec1.Free;
Rec2.Free;
end;
end;
var
Model: TOrmModel;
Master, Slave1, Slave2: TRestServerDB;
MasterAccess: TRestClientUri;
IDs: TIDDynArray;
Rec: TOrmPeopleVersioned;
Slave2Callback: IServiceRecordVersionCallback;
i, n: integer;
timeout: Int64;
function CreateServer(const DBFileName: TFileName;
DeleteDBFile: boolean): TRestServerDB;
begin
if DeleteDBFile then
DeleteFile(DBFileName);
result := TRestServerDB.Create(TOrmModel.Create(Model), DBFileName, false, '');
result.Model.Owner := result;
result.DB.Synchronous := smOff;
result.DB.LockingMode := lmExclusive;
result.Server.CreateMissingTables;
end;
procedure CreateMaster(DeleteDBFile: boolean);
var
serv: TRestHttpServer;
ws: TRestHttpClientWebsockets;
begin
Master := CreateServer('testversion' + DBExt, DeleteDBFile);
if Test is TTestBidirectionalRemoteConnection then
begin
serv := TTestBidirectionalRemoteConnection(Test).HttpServer;
Test.check(serv.AddServer(Master));
serv.WebSocketsEnable(Master, 'key2')^.SetFullLog;
ws := TRestHttpClientWebsockets.Create(
'127.0.0.1', HTTP_DEFAULTPORT, TOrmModel.Create(Model));
ws.Model.Owner := ws;
ws.WebSockets.Settings.SetFullLog;
Test.check(ws.WebSocketsUpgrade('key2') = '');
MasterAccess := ws;
end
else
MasterAccess := TRestClientDB.Create(Master);
end;
begin
Model := TOrmModel.Create(
[TOrmPeople, TOrmPeopleVersioned, TOrmTableDeleted], 'root0');
Master := CreateServer(SQLITE_MEMORY_DATABASE_NAME, true);
try
Rec := TOrmPeopleVersioned.Create;
try
for i := 1 to 20 do
Master.Orm.Add(Rec, true);
Master.Orm.Delete(TOrmPeopleVersioned, 'RowID>?', [2]);
finally
Rec.Free;
end;
finally
Master.Free;
end;
CreateMaster(true);
Slave1 := CreateServer('testversionreplicated' + DBExt, true);
Slave2 := CreateServer('testversioncallback' + DBExt, true);
try
Rec := TOrmPeopleVersioned.CreateAndFillPrepare(
StringFromFile(test.WorkDir + 'Test1.json'));
try
// Rec contains 1001 input rows of data
TestMasterSlave(Master, Slave1, MasterAccess);
TestMasterSlave(Master, Slave2, MasterAccess);
n := Rec.FillTable.RowCount;
Test.check(n > 100);
for i := 0 to 9 do
begin
// first test raw direct add
Test.check(Rec.FillOne);
Master.Server.Add(Rec, true, true);
end;
TestMasterSlave(Master, Slave1, MasterAccess);
if Test is TTestBidirectionalRemoteConnection then
begin
Test.check(
TTestBidirectionalRemoteConnection(Test).HttpServer.RemoveServer(Master));
TTestBidirectionalRemoteConnection(Test).HttpServer.RemoveServer(Master);
end;
Master.Free; // test TRestServer.InternalRecordVersionMaxFromExisting
MasterAccess.Free;
CreateMaster(false);
MasterAccess.Client.BatchStart(TOrmPeopleVersioned);
while Rec.FillOne do
// fast add via Batch
Test.check(MasterAccess.Client.BatchAdd(Rec, true, true) >= 0);
Test.check(MasterAccess.Client.BatchSend(IDs) = HTTP_SUCCESS);
Test.check(n = length(IDs) + 10);
Test.check(Rec.FillRewind);
for i := 0 to 9 do
Test.check(Rec.FillOne);
for i := 0 to high(IDs) do
if Rec.FillOne then
Test.check(IDs[i] = Rec.IDValue)
else
Test.check(false);
TestMasterSlave(Master, Slave1, MasterAccess);
TestMasterSlave(Master, Slave2, MasterAccess);
if Test is TTestBidirectionalRemoteConnection then
begin
// asynchronous synchronization via websockets
Test.check(Master.RecordVersionSynchronizeMasterStart(true));
Test.check(Slave2.RecordVersionSynchronizeSlaveStart(
TOrmPeopleVersioned, MasterAccess, nil));
end
else
begin
// direct synchronization within the same process
Slave2Callback := TServiceRecordVersionCallback.Create(
Slave2, MasterAccess, TOrmPeopleVersioned, nil);
Master.RecordVersionSynchronizeSubscribeMaster(TOrmPeopleVersioned,
Slave2.Server.RecordVersionCurrent(TOrmPeopleVersioned),
Slave2Callback);
end;
Test.check(Rec.FillRewind);
for i := 0 to 20 do
begin
Test.check(Rec.FillOne);
Rec.YearOfBirth := Rec.YearOfBirth + 1;
if i and 3 = 1 then
Test.check(Master.Server.Delete(TOrmPeopleVersioned, Rec.IDValue))
else
Test.check(Master.Server.Update(Rec, 'YearOfBirth'));
if i and 3 = 2 then
begin
Rec.YearOfBirth := Rec.YearOfBirth + 4;
Test.check(Master.Server.Update(Rec), 'update twice to increase Version');
end;
end;
//Test.check(Rec.FillRewind); would fail TestMasterSlave expectations
MasterAccess.Client.BatchStart(TOrmPeopleVersioned);
for i := 0 to 9 do
begin
Test.check(Rec.FillOne);
Rec.YearOfBirth := Rec.YearOfBirth + 10;
Test.check(MasterAccess.Client.BatchUpdate(Rec, 'YearOfBirth') >= 0);
end;
Test.check(MasterAccess.Client.BatchSend(IDs) = HTTP_SUCCESS);
TestMasterSlave(Master, Slave1, MasterAccess);
TestMasterSlave(Master, Slave1, MasterAccess);
if Test is TTestBidirectionalRemoteConnection then
begin
timeout := GetTickCount64 + 3000;
repeat
sleep(1)
until (GetTickCount64 > timeout) or // wait all callbacks to be received
(Slave2.Server.RecordVersionCurrent(TOrmPeopleVersioned) =
Master.Server.RecordVersionCurrent(TOrmPeopleVersioned));
Test.check(Slave2.RecordVersionSynchronizeSlaveStop(TOrmPeopleVersioned));
end;
TestMasterSlave(Master, Slave2, nil);
TestMasterSlave(Master, Slave2, MasterAccess);
finally
Rec.Free;
end;
if Test is TTestBidirectionalRemoteConnection then
TTestBidirectionalRemoteConnection(Test).HttpServer.RemoveServer(Master);
finally
Slave2Callback := nil;
Slave1.Free; // warning: Free should be in this order for callbacks release
Slave2.Free;
Master.Free;
MasterAccess.Free;
Model.Free;
end;
end;
procedure TTestSQLite3Engine._TRecordVersion;
begin
TestMasterSlaveRecordVersion(self, '.db3');
end;
type
TOrmPeopleArray = class(TOrmPeople)
private
fInts: TIntegerDynArray;
fCurrency: TCurrencyDynArray;
{$ifdef PUBLISHRECORD}
fRec: TFTSMatchInfo;
{$endif PUBLISHRECORD}
fFileVersion: TFVs;
fU: RawUtf8;
published
{$ifdef PUBLISHRECORD}
property Rec: TFTSMatchInfo
read fRec write fRec;
{$endif PUBLISHRECORD}
property U: RawUtf8
read fU write fU;
property Ints: TIntegerDynArray
index 1 read fInts write fInts;
property Currency: TCurrencyDynArray
index 2 read fCurrency write fCurrency;
property FileVersion: TFVs
index 3 read fFileVersion write fFileVersion;
end;
TOrmPeopleObject = class(TOrmPeople)
private
fPersistent: TCollTst;
fU: TRawUtf8List;
public
/// will create internal U/Persistent instances
constructor Create; override;
/// will release internal U/Persistent
destructor Destroy; override;
published
property U: TRawUtf8List
read fU;
property Persistent: TCollTst
read fPersistent;
end;
TOrmPeopleID = type TID; // validate ON DELETE SET DEFAULT at ORM level
TOrmPeopleToBeDeletedID = type TID; // validate ON DELETE CASCADE at ORM level
TOrmCustomProps = class(TOrmPeople)
protected
fGUid: TGuid;
fPeopleID: TID;
fPeople: TOrmPeopleID;
fPeopleCascade: TOrmPeopleToBeDeletedID;
{$ifdef PUBLISHRECORD}
fGUidXE6: TGuid;
{$endif PUBLISHRECORD}
class procedure InternalRegisterCustomProperties(Props: TOrmProperties); override;
public
property guid: TGuid
read fGUid write fGUid;
published
property PeopleID: TID
read fPeopleID write fPeopleID;
property People: TOrmPeopleID // ON DELETE SET DEFAULT
read fPeople write fPeople;
property PeopleCascade: TOrmPeopleToBeDeletedID // ON DELETE CASCADE
read fPeopleCascade write fPeopleCascade;
{$ifdef PUBLISHRECORD}
property GUidXE6: TGuid
read fGUidXE6 write fGUidXE6;
{$endif PUBLISHRECORD}
end;
TOrmFtsTest = class(TOrmFTS3)
private
fSubject: RawUtf8;
fBody: RawUtf8;
published
property Subject: RawUtf8
read fSubject write fSubject;
property Body: RawUtf8
read fBody write fBody;
end;
TOrmDali1 = class(TOrmVirtualTableAutoID)
private
fYearOfBirth: integer;
fFirstName: RawUtf8;
fYearOfDeath: word;
published
property FirstName: RawUtf8
read fFirstName write fFirstName;
property YearOfBirth: integer
read fYearOfBirth write fYearOfBirth;
property YearOfDeath: word
read fYearOfDeath write fYearOfDeath;
end;
TOrmDali2 = class(TOrmDali1);
{ TOrmPeopleObject }
constructor TOrmPeopleObject.Create;
begin
inherited;
fPersistent := TCollTst.Create;
fU := TRawUtf8List.Create;
end;
destructor TOrmPeopleObject.Destroy;
begin
Persistent.Free;
U.Free;
inherited;
end;
class procedure TOrmCustomProps.InternalRegisterCustomProperties(Props: TOrmProperties);
begin
Props.RegisterCustomPropertyFromTypeName(self, 'TGuid', 'Guid',
@TOrmCustomProps(nil).fGUid, [aIsUnique], 38);
end;
/// will be re-used by both TTestSQLite3Engine and TTestExternalDatabase
procedure InternalTestMany(Test: TSynTestCase; aClient: TRestOrmClientUri);
var
MS: TOrmASource;
MD, MD2: TOrmADest;
i: integer;
sID, dID: array[1..100] of Integer;
res: TIDDynArray;
procedure CheckOK;
begin
if Test.CheckFailed(MS.FillTable <> nil) then
exit;
Test.check(MS.FillTable.RowCount >= length(sID));
while MS.FillOne do
begin
Test.check(MS.DestList.Source.fID = MS.fID);
Test.check(MS.DestList.Dest.SignatureTime <> 0);
MS.ClearProperties;
MS.DestList.Source.ClearProperties;
MS.DestList.Dest.ClearProperties;
end;
MS.FillClose;
end;
begin
MS := TOrmASource.Create;
MD := TOrmADest.Create;
with Test do
try
MD.fSignatureTime := TimeLogNow;
MS.fSignatureTime := MD.fSignatureTime;
check(MS.DestList <> nil);