forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.orm.extdb.pas
1370 lines (1308 loc) · 50.2 KB
/
test.orm.extdb.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 process over external SQL DB engines
// - 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.extdb;
interface
{$I ..\src\mormot.defines.inc}
uses
sysutils,
mormot.core.base,
mormot.core.os,
mormot.core.text,
mormot.core.buffers,
mormot.core.unicode,
mormot.core.datetime,
mormot.core.rtti,
mormot.crypt.core,
mormot.core.data,
mormot.core.variants,
mormot.core.json,
mormot.core.log,
mormot.core.mustache,
mormot.core.test,
mormot.db.core,
mormot.db.sql,
mormot.db.sql.sqlite3,
mormot.db.sql.oledb,
mormot.db.nosql.bson,
mormot.db.raw.sqlite3,
mormot.db.raw.sqlite3.static,
mormot.db.proxy,
mormot.orm.core,
mormot.orm.storage,
mormot.orm.sql,
mormot.orm.rest,
mormot.orm.client,
mormot.orm.server,
mormot.soa.core,
mormot.rest.core,
mormot.rest.client,
mormot.rest.server,
mormot.rest.memserver,
mormot.rest.sqlite3,
mormot.rest.http.server,
mormot.rest.http.client,
test.core.base,
test.core.data,
test.orm.sqlite3;
type
/// a test case which will test most external DB functions of the
// mormot.orm.sql.pas unit
// - the external DB will be in fact a SQLite3 instance, expecting a
// test.db3 file available in the current directory, populated with
// some TOrmPeople rows
// - note that SQL statement caching at SQLite3 engine level makes those test
// 2 times faster: nice proof of performance improvement
TTestExternalDatabase = class(TSynTestCase)
protected
fExternalModel: TOrmModel;
fPeopleData: TOrmTable;
/// called by ExternalViaREST/ExternalViaVirtualTable and
// ExternalViaRESTWithChangeTracking tests method
procedure Test(StaticVirtualTableDirect, TrackChanges: boolean);
public
/// release used instances (e.g. server) and memory
procedure CleanUp; override;
published
/// test SynDB connection remote access via HTTP
procedure _SynDBRemote;
/// test TSqlDBConnectionProperties persistent as JSON
procedure DBPropertiesPersistence;
/// initialize needed RESTful client (and server) instances
// - i.e. a RESTful direct access to an external DB
procedure ExternalRecords;
/// check the SQL auto-adaptation features
procedure AutoAdaptSQL;
/// check the per-db encryption
// - the testpass.db3-wal file is not encrypted, but the main
// testpass.db3 file will
procedure CryptedDatabase;
/// test external DB implementation via faster REST calls
// - will mostly call directly the TRestStorageExternal instance,
// bypassing the Virtual Table mechanism of SQLite3
procedure ExternalViaREST;
/// test external DB implementation via slower Virtual Table calls
// - using the Virtual Table mechanism of SQLite3 is more than 2 times
// slower than direct REST access
procedure ExternalViaVirtualTable;
/// test external DB implementation via faster REST calls and change tracking
// - a TOrmHistory table will be used to store record history
procedure ExternalViaRESTWithChangeTracking;
{$ifndef CPU64}
{$ifdef OSWINDOWS}
/// test external DB using the JET engine
procedure JETDatabase;
{$endif OSWINDOWS}
{$endif CPU64}
{$ifdef OSWINDOWS}
{$ifdef USEZEOS}
/// test external Firebird embedded engine via Zeos/ZDBC (if available)
procedure FirebirdEmbeddedViaZDBCOverHTTP;
{$endif USEZEOS}
{$endif OSWINDOWS}
end;
type
TOrmPeopleExt = class(TOrm)
private
fFirstName: RawUtf8;
fLastName: RawUtf8;
fData: RawBlob;
fYearOfBirth: integer;
fYearOfDeath: word;
fValue: TVariantDynArray;
fLastChange: TModTime;
fCreatedAt: TCreateTime;
published
property FirstName: RawUtf8
index 40 read fFirstName write fFirstName;
property LastName: RawUtf8
index 40 read fLastName write fLastName;
property Data: RawBlob
read fData write fData;
property YearOfBirth: integer
read fYearOfBirth write fYearOfBirth;
property YearOfDeath: word
read fYearOfDeath write fYearOfDeath;
property Value: TVariantDynArray
read fValue write fValue;
property LastChange: TModTime
read fLastChange;
property CreatedAt: TCreateTime
read fCreatedAt write fCreatedAt;
end;
TOrmOnlyBlob = class(TOrm)
private
fData: RawBlob;
published
property Data: RawBlob
read fData write fData;
end;
TOrmTestJoin = class(TOrm)
private
fName: RawUtf8;
fPeople: TOrmPeopleExt;
published
property Name: RawUtf8
index 30 read fName write fName;
property People: TOrmPeopleExt
read fPeople write fPeople;
end;
TOrmMyHistory = class(TOrmHistory);
implementation
{$ifdef OSWINDOWS}
{$ifdef USEZEOS}
uses
mormot.db.sql.zeos;
{$endif USEZEOS}
{$endif OSWINDOWS}
type
// class hooks to access DMBS property for TTestExternalDatabase.AutoAdaptSQL
TSqlDBConnectionPropertiesHook = class(TSqlDBConnectionProperties);
TRestStorageExternalHook = class(TRestStorageExternal);
{ TTestExternalDatabase }
procedure TTestExternalDatabase.ExternalRecords;
var
sql: RawUtf8;
begin
if CheckFailed(fExternalModel = nil) then
exit; // should be called once
fExternalModel := TOrmModel.Create([TOrmPeopleExt, TOrmOnlyBlob, TOrmTestJoin,
TOrmASource, TOrmADest, TOrmADests, TOrmPeople, TOrmMyHistory]);
ReplaceParamsByNames(ToUtf8(StringOfChar('?', 200)), sql);
CheckHash(sql, $AD27D1E0, 'excludes :IF :OF');
end;
procedure TTestExternalDatabase.AutoAdaptSQL;
var
SqlOrigin, s: RawUtf8;
Props: TSqlDBConnectionProperties;
Server: TRestServer;
Ext: TRestStorageExternalHook;
procedure Test(aDBMS: TSqlDBDefinition; AdaptShouldWork: boolean;
const SQLExpected: RawUtf8 = '');
var
SQL: RawUtf8;
begin
SQL := SqlOrigin;
TSqlDBConnectionPropertiesHook(Props).fDBMS := aDBMS;
Check((Props.DBMS = aDBMS) or (aDBMS = dUnknown));
Check(Ext.AdaptSQLForEngineList(SQL) = AdaptShouldWork);
CheckUtf8(SameTextU(SQL, SQLExpected) or
not AdaptShouldWork, SQLExpected + #13#10 + SQL);
end;
procedure Test2(const Orig, Expected: RawUtf8);
var
DBMS: TSqlDBDefinition;
begin
SqlOrigin := Orig;
for DBMS := low(DBMS) to high(DBMS) do
Test(DBMS, true, Expected);
end;
begin
check(ReplaceParamsByNumbers('', s) = 0);
check(s = '');
check(ReplaceParamsByNumbers('toto titi', s) = 0);
check(s = 'toto titi');
check(ReplaceParamsByNumbers('toto=? titi', s) = 1);
check(s = 'toto=$1 titi');
check(ReplaceParamsByNumbers('toto=? titi=?', s) = 2);
check(s = 'toto=$1 titi=$2');
check(ReplaceParamsByNumbers('toto=? titi=? and a=''''', s) = 2);
check(s = 'toto=$1 titi=$2 and a=''''');
check(ReplaceParamsByNumbers('toto=? titi=? and a=''dd''', s) = 2);
check(s = 'toto=$1 titi=$2 and a=''dd''');
check(ReplaceParamsByNumbers('toto=? titi=? and a=''d''''d''', s) = 2);
check(s = 'toto=$1 titi=$2 and a=''d''''d''');
check(ReplaceParamsByNumbers('toto=? titi=? and a=''d?d''', s) = 2);
check(s = 'toto=$1 titi=$2 and a=''d?d''');
check(ReplaceParamsByNumbers('1?2?3?4?5?6?7?8?9?10?11?12? x', s) = 12);
check(s = '1$12$23$34$45$56$67$78$89$910$1011$1112$12 x');
checkequal(BoundArrayToJsonArray(TRawUtf8DynArrayFrom([])), '');
checkequal(BoundArrayToJsonArray(TRawUtf8DynArrayFrom(['1'])), '{1}');
checkequal(BoundArrayToJsonArray(TRawUtf8DynArrayFrom(['''1'''])), '{"1"}');
checkequal(BoundArrayToJsonArray(TRawUtf8DynArrayFrom(['1', '2', '3'])), '{1,2,3}');
checkequal(BoundArrayToJsonArray(TRawUtf8DynArrayFrom(['''1''', '2', '''3'''])),
'{"1",2,"3"}');
checkequal(BoundArrayToJsonArray(TRawUtf8DynArrayFrom(['''1"1''', '2',
'''"3\'''])), '{"1\"1",2,"\"3\\"}');
check(TSqlDBConnectionProperties.IsSQLKeyword(dUnknown, 'SELEct'));
check(not TSqlDBConnectionProperties.IsSQLKeyword(dUnknown, 'toto'));
check(TSqlDBConnectionProperties.IsSQLKeyword(dOracle, 'SELEct'));
check(not TSqlDBConnectionProperties.IsSQLKeyword(dOracle, 'toto'));
check(TSqlDBConnectionProperties.IsSQLKeyword(dOracle, ' auDIT '));
check(not TSqlDBConnectionProperties.IsSQLKeyword(dMySQL, ' auDIT '));
check(TSqlDBConnectionProperties.IsSQLKeyword(dSQLite, 'SELEct'));
check(TSqlDBConnectionProperties.IsSQLKeyword(dSQLite, 'clustER'));
check(not TSqlDBConnectionProperties.IsSQLKeyword(dSQLite, 'value'));
Server := TRestServerFullMemory.Create(fExternalModel);
try
Props := TSqlDBSQLite3ConnectionProperties.Create(
SQLITE_MEMORY_DATABASE_NAME, '', '', '');
try
VirtualTableExternalMap(fExternalModel, TOrmPeopleExt, Props,
'SampleRecord').MapField('LastChange', 'Changed');
Ext := TRestStorageExternalHook.Create(
TOrmPeopleExt, Server.OrmInstance as TRestOrmServer);
try
Test2('select rowid,firstname from PeopleExt where rowid=2',
'select id,firstname from SampleRecord where id=2');
Test2('select rowid,firstname from PeopleExt where rowid=?',
'select id,firstname from SampleRecord where id=?');
Test2('select rowid,firstname from PeopleExt where rowid>=?',
'select id,firstname from SampleRecord where id>=?');
Test2('select rowid,firstname from PeopleExt where rowid<?',
'select id,firstname from SampleRecord where id<?');
Test2('select rowid,firstname from PeopleExt where rowid=2 and lastname=:(''toto''):',
'select id,firstname from SampleRecord where id=2 and lastname=:(''toto''):');
Test2('select rowid,firstname from PeopleExt where rowid=2 and rowID=:(2): order by rowid',
'select id,firstname from SampleRecord where id=2 and id=:(2): order by id');
Test2('select rowid,firstname from PeopleExt where rowid=2 or lastname=:(''toto''):',
'select id,firstname from SampleRecord where id=2 or lastname=:(''toto''):');
Test2('select rowid,firstname from PeopleExt where rowid=2 and not lastname like ?',
'select id,firstname from SampleRecord where id=2 and not lastname like ?');
Test2('select rowid,firstname from PeopleExt where rowid=2 and not (lastname like ?)',
'select id,firstname from SampleRecord where id=2 and not (lastname like ?)');
Test2('select rowid,firstname from PeopleExt where (rowid=2 and lastname="toto") or lastname like ?',
'select id,firstname from SampleRecord where (id=2 and lastname="toto") or lastname like ?');
Test2('select rowid,firstname from PeopleExt where (rowid=2 or lastname=:("toto"):) and lastname like ?',
'select id,firstname from SampleRecord where (id=2 or lastname=:("toto"):) and lastname like ?');
Test2('select rowid,firstname from PeopleExt where (rowid=2) and (lastname="toto" or lastname like ?)',
'select id,firstname from SampleRecord where (id=2) and (lastname="toto" or lastname like ?)');
Test2('select rowid,firstname from PeopleExt where (rowid=2) and (lastname=:("toto"): or (lastname like ?))',
'select id,firstname from SampleRecord where (id=2) and (lastname=:("toto"): or (lastname like ?))');
Test2('select rowid,firstname from PeopleExt where rowid=2 order by RowID',
'select id,firstname from SampleRecord where id=2 order by ID');
Test2('select rowid,firstname from PeopleExt where rowid=2 order by RowID DeSC',
'select id,firstname from SampleRecord where id=2 order by ID desc');
Test2('select rowid,firstname from PeopleExt order by RowID,firstName DeSC',
'select id,firstname from SampleRecord order by ID,firstname desc');
Test2('select rowid, firstName from PeopleExt order by RowID, firstName',
'select id,firstname from SampleRecord order by ID,firstname');
Test2('select rowid, firstName from PeopleExt order by RowID, firstName asC',
'select id,firstname from SampleRecord order by ID,firstname');
Test2('select rowid,firstname from PeopleExt where firstname like :(''test''): order by lastname',
'select id,firstname from SampleRecord where firstname like :(''test''): order by lastname');
Test2(' select COUNT(*) from PeopleExt ',
'select count(*) from SampleRecord');
Test2('select count(*) from PeopleExt where rowid=2',
'select count(*) from SampleRecord where id=2');
Test2('select count(*) from PeopleExt where rowid=2 /*tobeignored*/',
'select count(*) from SampleRecord where id=2');
Test2('select count(*) from PeopleExt where /*tobeignored*/ rowid=2',
'select count(*) from SampleRecord where id=2');
Test2('select Distinct(firstname) , max(lastchange)+100 from PeopleExt where rowid >= :(2):',
'select Distinct(FirstName),max(Changed)+100 as LastChange from SampleRecord where ID>=:(2):');
Test2('select Distinct(lastchange) , max(rowid)-100 as newid from PeopleExt where rowid >= :(2):',
'select Distinct(Changed) as lastchange,max(id)-100 as newid from SampleRecord where ID>=:(2):');
SqlOrigin := 'select rowid,firstname from PeopleExt where rowid=2 limit 2';
Test(dUnknown, false);
Test(dDefault, false);
Test(dOracle, true,
'select id,firstname from SampleRecord where rownum<=2 and id=2');
Test(dMSSQL, true, 'select top(2) id,firstname from SampleRecord where id=2');
Test(dJet, true, 'select top 2 id,firstname from SampleRecord where id=2');
Test(dMySQL, true, 'select id,firstname from SampleRecord where id=2 limit 2');
Test(dSQLite, true, 'select id,firstname from SampleRecord where id=2 limit 2');
SqlOrigin :=
'select rowid,firstname from PeopleExt where rowid=2 order by LastName limit 2';
Test(dUnknown, false);
Test(dDefault, false);
Test(dOracle, true,
'select id,firstname from SampleRecord where rownum<=2 and id=2 order by LastName');
Test(dMSSQL, true,
'select top(2) id,firstname from SampleRecord where id=2 order by LastName');
Test(dJet, true,
'select top 2 id,firstname from SampleRecord where id=2 order by LastName');
Test(dMySQL, true,
'select id,firstname from SampleRecord where id=2 order by LastName limit 2');
Test(dSQLite, true,
'select id,firstname from SampleRecord where id=2 order by LastName limit 2');
SqlOrigin :=
'select rowid,firstname from PeopleExt where firstname=:(''test''): limit 2';
Test(dUnknown, false);
Test(dDefault, false);
Test(dOracle, true,
'select id,firstname from SampleRecord where rownum<=2 and firstname=:(''test''):');
Test(dMSSQL, true,
'select top(2) id,firstname from SampleRecord where firstname=:(''test''):');
Test(dJet, true,
'select top 2 id,firstname from SampleRecord where firstname=:(''test''):');
Test(dMySQL, true,
'select id,firstname from SampleRecord where firstname=:(''test''): limit 2');
Test(dSQLite, true,
'select id,firstname from SampleRecord where firstname=:(''test''): limit 2');
SqlOrigin := 'select id,firstname from PeopleExt limit 2';
Test(dUnknown, false);
Test(dDefault, false);
Test(dOracle, true, 'select id,firstname from SampleRecord where rownum<=2');
Test(dMSSQL, true, 'select top(2) id,firstname from SampleRecord');
Test(dJet, true, 'select top 2 id,firstname from SampleRecord');
Test(dMySQL, true, 'select id,firstname from SampleRecord limit 2');
Test(dSQLite, true, 'select id,firstname from SampleRecord limit 2');
SqlOrigin := 'select id,firstname from PeopleExt order by firstname limit 2';
Test(dUnknown, false);
Test(dDefault, false);
Test(dOracle, true,
'select id,firstname from SampleRecord where rownum<=2 order by firstname');
Test(dMSSQL, true,
'select top(2) id,firstname from SampleRecord order by firstname');
Test(dJet, true,
'select top 2 id,firstname from SampleRecord order by firstname');
Test(dMySQL, true,
'select id,firstname from SampleRecord order by firstname limit 2');
Test(dSQLite, true,
'select id,firstname from SampleRecord order by firstname limit 2');
SqlOrigin := 'SELECT RowID,firstname FROM PeopleExt WHERE :(3001): ' +
'BETWEEN firstname AND RowID LIMIT 1';
Test(dSQLite, false);
finally
Ext.Free;
end;
finally
Props.Free;
end;
finally
Server.Free;
end;
end;
procedure TTestExternalDatabase.CleanUp;
begin
FreeAndNil(fExternalModel);
FreeAndNil(fPeopleData);
inherited;
end;
procedure TTestExternalDatabase.ExternalViaREST;
begin
Test(true, false);
end;
procedure TTestExternalDatabase.ExternalViaVirtualTable;
begin
Test(false, false);
end;
procedure TTestExternalDatabase.ExternalViaRESTWithChangeTracking;
begin
Test(true, true);
end;
{$ifdef OSWINDOWS}
{$ifdef USEZEOS}
const
// if this library file is available and USEZEOS conditional is set, will run
// TTestExternalDatabase.FirebirdEmbeddedViaODBC
// !! download driver from http://www.firebirdsql.org/en/odbc-driver
FIREBIRDEMBEDDEDDLL =
'd:\Dev\Lib\SQLite3\Samples\15 - External DB performance\Firebird' +
{$ifdef CPU64} '64' + {$endif=} '\fbembed.dll';
procedure TTestExternalDatabase.FirebirdEmbeddedViaZDBCOverHTTP;
var
R: TOrmPeople;
Model: TOrmModel;
Props: TSqlDBConnectionProperties;
Server: TRestServerDB;
Http: TRestHttpServer;
Client: TRestClientURI;
i, n: integer;
ids: array[0..3] of TID;
res: TIDDynArray;
begin
if not FileExists(FIREBIRDEMBEDDEDDLL) then
exit;
Model := TOrmModel.Create([TOrmPeople]);
try
R := TOrmPeople.Create;
try
DeleteFile('test.fdb'); // will be re-created at first connection
Props := TSqlDBZeosConnectionProperties.Create(
TSqlDBZeosConnectionProperties.URI(
dFirebird, '', FIREBIRDEMBEDDEDDLL, False), 'test.fdb', '', '');
try
VirtualTableExternalMap(Model, TOrmPeople, Props, 'peopleext').
MapFields(['ID', 'key',
'YearOfBirth', 'yob']);
Server := TRestServerDB.Create(Model, SQLITE_MEMORY_DATABASE_NAME);
try
Server.CreateMissingTables;
Http := TRestHttpServer.Create(HTTP_DEFAULTPORT, Server);
Client := TRestHttpClient.Create('localhost', HTTP_DEFAULTPORT,
TOrmModel.Create(Model));
Client.Model.Owner := Client;
try
R.FillPrepare(fPeopleData);
if not CheckFailed(R.FillContext <> nil) then
begin
Client.BatchStart(TOrmPeople, 5000);
n := 0;
while R.FillOne do
begin
R.YearOfBirth := n;
Client.BatchAdd(R, true);
inc(n);
end;
Check(Client.BatchSend(res) = HTTP_SUCCESS);
Check(length(res) = n);
for i := 1 to 100 do
begin
R.ClearProperties;
Check(Client.Retrieve(res[Random(n)], R));
Check(R.ID <> 0);
Check(res[R.YearOfBirth] = R.ID);
end;
end;
for i := 0 to high(ids) do
begin
R.YearOfBirth := i;
ids[i] := Client.Add(R, true);
end;
for i := 0 to high(ids) do
begin
Check(Client.Retrieve(ids[i], R));
Check(R.YearOfBirth = i);
end;
for i := 0 to high(ids) do
begin
Client.BatchStart(TOrmPeople);
Client.BatchDelete(ids[i]);
Check(Client.BatchSend(res) = HTTP_SUCCESS);
Check(length(res) = 1);
Check(res[0] = HTTP_SUCCESS);
end;
for i := 0 to high(ids) do
Check(not Client.Retrieve(ids[i], R));
R.ClearProperties;
for i := 0 to high(ids) do
begin
R.IDValue := ids[i];
Check(Client.Update(R), 'test locking');
end;
for i := 0 to high(ids) do
begin
R.YearOfBirth := i;
ids[i] := Client.Add(R, true);
end;
for i := 0 to high(ids) do
begin
Check(Client.Retrieve(ids[i], R));
Check(R.YearOfBirth = i);
end;
finally
Client.Free;
Http.Free;
end;
finally
Server.Free;
end;
finally
Props.Free;
end;
finally
R.Free;
end;
finally
Model.Free;
end;
end;
{$endif USEZEOS}
{$endif OSWINDOWS}
{$ifndef CPU64}
{$ifdef OSWINDOWS}
procedure TTestExternalDatabase.JETDatabase;
var
R: TOrmPeople;
Model: TOrmModel;
Props: TSqlDBConnectionProperties;
Client: TRestClientDB;
i, n, ID, LastID: integer;
begin
Model := TOrmModel.Create([TOrmPeople]);
try
R := TOrmPeople.Create;
R.FillPrepare(fPeopleData);
if not CheckFailed(R.FillContext <> nil) then
try
DeleteFile('test.mdb');
Props := TSqlDBOleDBJetConnectionProperties.Create('test.mdb', '', '', '');
try
VirtualTableExternalRegister(Model, TOrmPeople, Props, '');
Client := TRestClientDB.Create(
Model, nil, SQLITE_MEMORY_DATABASE_NAME, TRestServerDB);
try
Client.Server.CreateMissingTables;
Client.Orm.TransactionBegin(TOrmPeople);
n := 0;
while R.FillOne do
begin
inc(n);
Check(Client.Orm.Add(R, true, true) =
R.FillContext.Table.GetID(n));
if n > 999 then
break; // Jet is very slow e.g. within the Delphi IDE
end;
Client.Orm.Commit;
R.FirstName := '';
R.LastName := '';
R.YearOfBirth := 100;
R.YearOfDeath := 0;
R.Data := '';
LastID := Client.Orm.Add(R, true);
for i := 1 to n do
begin
R.ClearProperties;
ID := R.FillContext.Table.GetID(n);
Check(Client.Orm.Retrieve(ID, R));
Check(R.IDValue = ID);
Check(R.ID = ID);
Check(R.FirstName <> '');
Check(R.YearOfBirth >= 1400);
Check(R.YearOfDeath >= 1468);
end;
Check(Client.Orm.Retrieve(LastID, R));
Check(R.FirstName = '');
Check(R.LastName = '');
Check(R.YearOfBirth = 100);
Check(R.YearOfDeath = 0);
Check(R.Data = '');
finally
Client.Free;
end;
finally
Props.Free;
end;
finally
R.Free;
end;
finally
Model.Free;
end;
end;
{$endif OSWINDOWS}
{$endif CPU64}
procedure TTestExternalDatabase._SynDBRemote;
var
Props: TSqlDBConnectionProperties;
procedure DoTest(proxy: TSqlDBConnectionProperties; msg: PUTF8Char);
procedure DoTests;
var
res: ISqlDBRows;
id, lastid, n, n1: integer;
IDs: TIntegerDynArray;
Row, RowDoc: variant;
procedure DoInsert;
var
i: integer;
begin
for i := 0 to high(IDs) do
Check(proxy.ExecuteNoResult(
'INSERT INTO People (ID,FirstName,LastName,YearOfBirth,YearOfDeath) ' +
'VALUES (?,?,?,?,?)', [IDs[i], 'FirstName New ' + Int32ToUtf8(i),
'New Last', i + 1400, 1519]) = 1);
end;
function DoCount: integer;
var
res: ISqlDBRows;
begin
res := proxy.Execute(
'select count(*) from People where YearOfDeath=?', [1519]);
{%H-}Check(res.Step);
result := res.ColumnInt(0);
end;
var
log: ISynLog;
begin
log := TSynLogTestLog.Enter(proxy, msg);
if proxy <> Props then
Check(proxy.UserID = 'user');
proxy.ExecuteNoResult('delete from people where ID>=?', [50000]);
res := proxy.Execute('select * from People where YearOfDeath=?', [1519]);
Check(res <> nil);
n := 0;
lastid := 0;
while res.Step do
begin
id := res.ColumnInt('ID');
Check(id <> lastid);
Check(id > 0);
lastid := id;
Check(res.ColumnInt('YearOfDeath') = 1519);
inc(n);
end;
Check(n = DoCount);
n1 := n;
n := 0;
Row := res.RowData;
if res.Step({rewind=}true) then
repeat
Check(Row.ID > 0);
Check(Row.YearOfDeath = 1519);
res.RowDocVariant(RowDoc);
Check(RowDoc.ID = Row.ID);
Check(_Safe(RowDoc)^.i['YearOfDeath'] = 1519);
inc(n);
until not res.Step;
res.ReleaseRows;
Check(n = n1);
SetLength(IDs, 50);
FillIncreasing(pointer(IDs), 50000, length(IDs));
proxy.ThreadSafeConnection.StartTransaction;
DoInsert;
proxy.ThreadSafeConnection.Rollback;
Check(DoCount = n);
proxy.ThreadSafeConnection.StartTransaction;
DoInsert;
proxy.ThreadSafeConnection.Commit;
n1 := DoCount;
Check(n1 = n + length(IDs));
proxy.ExecuteNoResult('delete from people where ID>=?', [50000]);
Check(DoCount = n);
end;
begin
try
DoTests;
finally
if proxy <> Props then
proxy.Free;
end;
end;
var
Server: TSqlDBServerAbstract;
const
ADDR = '127.0.0.1:' + HTTP_DEFAULTPORT;
begin
Props := TSqlDBSQLite3ConnectionProperties.Create('test.db3', '', '', '');
try
DoTest(Props, 'raw Props');
DoTest(TSqlDBRemoteConnectionPropertiesTest.Create(
Props, 'user', 'pass', TSqlDBProxyConnectionProtocol), 'proxy test');
DoTest(TSqlDBRemoteConnectionPropertiesTest.Create(
Props, 'user', 'pass', TSqlDBRemoteConnectionProtocol), 'remote test');
Server := TSqlDBServerRemote.Create(
Props, 'root', HTTP_DEFAULTPORT, 'user', 'pass');
try
DoTest(TSqlDBSocketConnectionProperties.Create(
ADDR, 'root', 'user', 'pass'), 'socket');
{$ifdef USEWININET}
DoTest(TSqlDBWinHTTPConnectionProperties.Create(
ADDR, 'root', 'user', 'pass'), 'winhttp');
DoTest(TSqlDBWinINetConnectionProperties.Create(
ADDR, 'root', 'user', 'pass'), 'wininet');
{$endif USEWININET}
{$ifdef USELIBCURL}
DoTest(TSqlDBCurlConnectionProperties.Create(
ADDR, 'root', 'user', 'pass'), 'libcurl');
{$endif USELIBCURL}
finally
Server.Free;
end;
finally
Props.Free;
end;
end;
procedure TTestExternalDatabase.DBPropertiesPersistence;
var
Props: TSqlDBConnectionProperties;
json: RawUtf8;
begin
Props := TSqlDBSQLite3ConnectionProperties.Create('server', '', '', '');
json := Props.DefinitionToJson(14);
Check(json = '{"Kind":"TSqlDBSQLite3ConnectionProperties",' +
'"ServerName":"server","DatabaseName":"","User":"","Password":""}');
Props.Free;
Props := TSqlDBSQLite3ConnectionProperties.Create('server', '', '', '1234');
json := Props.DefinitionToJson(14);
Check(json = '{"Kind":"TSqlDBSQLite3ConnectionProperties",' +
'"ServerName":"server","DatabaseName":"","User":"","Password":"MnVfJg=="}');
Props.DefinitionToFile(WorkDir + 'connectionprops.json');
Props.Free;
Props := TSqlDBConnectionProperties.CreateFromFile(WorkDir + 'connectionprops.json');
Check(Props.ClassType = TSqlDBSQLite3ConnectionProperties);
Check(Props.ServerName = 'server');
Check(Props.DatabaseName = '');
Check(Props.UserID = '');
Check(Props.PassWord = '1234');
Props.Free;
DeleteFile(WorkDir + 'connectionprops.json');
end;
procedure TTestExternalDatabase.CryptedDatabase;
var
R, R2: TOrmPeople;
Model: TOrmModel;
aID: integer;
Client, Client2: TRestClientDB;
Res: TIDDynArray;
procedure CheckFilledRow;
begin
Check(R.FillRewind);
while R.FillOne do
if not CheckFailed(R2.FillOne) then
begin
Check(R.ID <> 0);
Check(R2.ID <> 0);
Check(R.FirstName = R2.FirstName);
Check(R.LastName = R2.LastName);
Check(R.YearOfBirth = R2.YearOfBirth);
Check(R.YearOfDeath = R2.YearOfDeath);
end;
end;
{$ifdef NOSQLITE3STATIC}
const
password = '';
{$else}
const
password = 'pass';
{$endif NOSQLITE3STATIC}
begin
DeleteFile('testpass.db3');
Model := TOrmModel.Create([TOrmPeople]);
try
Client := TRestClientDB.Create(Model, nil, 'test.db3', TRestServerDB, false, '');
try
R := TOrmPeople.Create;
Assert(fPeopleData = nil);
fPeopleData := Client.Client.List([TOrmPeople], '*');
R.FillPrepare(fPeopleData);
try
Client2 := TRestClientDB.Create(
Model, nil, 'testpass.db3', TRestServerDB, false, password);
try
Client2.Server.DB.Synchronous := smOff;
Client2.Server.DB.LockingMode := lmExclusive;
Client2.Server.DB.WALMode := true;
Client2.Server.Server.CreateMissingTables;
Check(Client2.Client.TransactionBegin(TOrmPeople));
Check(Client2.Client.BatchStart(TOrmPeople));
Check(Client2.Client.BatchSend(Res) = 200, 'Void batch');
Check(Res = nil);
Client2.Client.Commit;
Check(Client2.Client.TransactionBegin(TOrmPeople));
Check(Client2.Client.BatchStart(TOrmPeople));
while R.FillOne do
begin
Check(R.ID <> 0);
Check(Client2.Client.BatchAdd(R, true) >= 0);
end;
Check(Client2.Client.BatchSend(Res) = 200, 'INSERT batch');
Client2.Client.Commit;
finally
Client2.Free;
end;
Check(IsSQLite3File('testpass.db3'));
Check(IsSQLite3FileEncrypted('testpass.db3') = (password <> ''), 'encrypt1');
// try to read then update the crypted file
Client2 := TRestClientDB.Create(
Model, nil, 'testpass.db3', TRestServerDB, false, password);
try
Client2.Server.DB.Synchronous := smOff;
Client2.Server.DB.LockingMode := lmExclusive;
R2 := TOrmPeople.CreateAndFillPrepare(Client2.Orm, '');
try
CheckFilledRow;
R2.FirstName := 'One';
aID := Client2.Orm.Add(R2, true);
Check(aID <> 0);
R2.FillPrepare(Client2.Orm, '');
CheckFilledRow;
R2.ClearProperties;
Check(R2.FirstName = '');
Check(Client2.Orm.Retrieve(aID, R2));
Check(R2.FirstName = 'One');
finally
R2.Free;
end;
finally
Client2.Free;
end;
Check(IsSQLite3File('testpass.db3'));
Check(IsSQLite3FileEncrypted('testpass.db3') = (password <> ''), 'encrypt2');
{$ifndef NOSQLITE3STATIC}
// now read it after uncypher
check(ChangeSQLEncryptTablePassWord('testpass.db3', password, ''));
Check(IsSQLite3File('testpass.db3'));
Check(not IsSQLite3FileEncrypted('testpass.db3'), 'encrypt3');
Client2 := TRestClientDB.Create(Model, nil, 'testpass.db3',
TRestServerDB, false, '');
try
R2 := TOrmPeople.CreateAndFillPrepare(Client2.Orm, '');
try
CheckFilledRow;
R2.ClearProperties;
Check(R2.FirstName = '');
Check(Client2.Orm.Retrieve(aID, R2));
Check(R2.FirstName = 'One');
finally
R2.Free;
end;
finally
Client2.Free;
end;
{$endif NOSQLITE3STATIC}
finally
R.Free;
end;
finally
Client.Free;
end;
finally
Model.Free;
end;
end;
procedure TTestExternalDatabase.Test(StaticVirtualTableDirect, TrackChanges: boolean);
const
BLOB_MAX = 1000;
var
RInt, RInt1: TOrmPeople;
RExt: TOrmPeopleExt;
RBlob: TOrmOnlyBlob;
RJoin: TOrmTestJoin;
RHist: TOrmMyHistory;
Tables: TRawUtf8DynArray;
i, n, aID: integer;
Orm: TRestOrmServer;
ok: Boolean;
BatchID, BatchIDUpdate, BatchIDJoined: TIDDynArray;
ids: array[0..3] of TID;
aExternalClient: TRestClientDB;
fProperties: TSqlDBConnectionProperties;
json: RawUtf8;
Start, Updated: TTimeLog; // will work with both TModTime and TCreateTime properties
procedure HistoryCheck(aIndex, aYOB: Integer; aEvent: TOrmHistoryEvent);
var
Event: TOrmHistoryEvent;
Timestamp: TModTime;
R: TOrmPeopleExt;
begin
RExt.ClearProperties;
Check(RHist.HistoryGet(aIndex, Event, Timestamp, RExt));
Check(Event = aEvent);
Check(Timestamp >= Start);
if Event = heDelete then
exit;
Check(RExt.ID = 400);
Check(RExt.FirstName = 'Franz36');
Check(RExt.YearOfBirth = aYOB);
R := RHist.HistoryGet(aIndex) as TOrmPeopleExt;
if CheckFailed(R <> nil) then
exit;
Check(R.ID = 400);
Check(R.FirstName = 'Franz36');
Check(R.YearOfBirth = aYOB);
R.Free;
end;
procedure HistoryChecks;
var
i: integer;
begin
RHist := TOrmMyHistory.CreateHistory(aExternalClient.Orm, TOrmPeopleExt, 400);
try
Check(RHist.HistoryCount = 504);
HistoryCheck(0, 1797, heAdd);
HistoryCheck(1, 1828, heUpdate);
HistoryCheck(2, 1515, heUpdate);
for i := 1 to 500 do
HistoryCheck(i + 2, i, heUpdate);
HistoryCheck(503, 0, heDelete);
finally
RHist.Free;
end;
end;
var
historyDB: TRestServerDB;
begin
// run tests over an in-memory SQLite3 external database (much faster than file)
DeleteFile('extdata.db3');
fProperties := TSqlDBSQLite3ConnectionProperties.Create('extdata.db3', '', '', '');
(fProperties.MainConnection as TSqlDBSQLite3Connection).Synchronous := smOff;
(fProperties.MainConnection as TSqlDBSQLite3Connection).LockingMode := lmExclusive;
Check(VirtualTableExternalMap(
fExternalModel, TOrmPeopleExt, fProperties, 'PeopleExternal').
MapField('ID', 'Key').
MapField('YearOfDeath', 'YOD').
MapAutoKeywordFields <> nil);
Check(VirtualTableExternalRegister(
fExternalModel, TOrmOnlyBlob, fProperties, 'OnlyBlobExternal'));
Check(VirtualTableExternalRegister(
fExternalModel, TOrmTestJoin, fProperties, 'TestJoinExternal'));
Check(VirtualTableExternalRegister(
fExternalModel, TOrmASource, fProperties, 'SourceExternal'));
Check(VirtualTableExternalRegister(
fExternalModel, TOrmADest, fProperties, 'DestExternal'));
Check(VirtualTableExternalRegister(
fExternalModel, TOrmADests, fProperties, 'DestsExternal'));
DeleteFile('testExternal.db3'); // need a file for backup testing
if TrackChanges and
StaticVirtualTableDirect then
begin
DeleteFile('history.db3');
historyDB := TRestServerDB.Create(
TOrmModel.Create([TOrmMyHistory], 'history'), 'history.db3', false);
end
else
historyDB := nil;
aExternalClient := TRestClientDB.Create(
fExternalModel, nil, 'testExternal.db3', TRestServerDB);
try
if historyDB <> nil then