-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathmormot.soa.codegen.pas
2239 lines (2109 loc) · 76.6 KB
/
mormot.soa.codegen.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
/// Interface-based SOA Code and Documentation Generator
// - 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 mormot.soa.codegen;
{
*****************************************************************************
SOA API Code and Documentation Generation
- ORM and SOA Logic Extraction from RTTI
- Documentation Extraction from Source Code Comments
- Doc/CodeGen wrapper Functions on Server Side
- FPC Dedicated Generators
- Compute Asynchronous Code from Synchronous Interface
- Generate Code and Doc from Command-Line
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
variants,
{$ifdef ISDELPHI}
typinfo, // for proper Delphi inlining
{$endif ISDELPHI}
mormot.core.base,
mormot.core.os,
mormot.core.buffers,
mormot.core.unicode,
mormot.core.text,
mormot.core.variants,
mormot.core.data,
mormot.core.datetime,
mormot.core.rtti,
mormot.core.json,
mormot.core.interfaces,
mormot.core.mustache,
mormot.orm.base,
mormot.orm.core,
mormot.orm.rest,
mormot.soa.core,
mormot.soa.server,
mormot.rest.core,
mormot.rest.server,
mormot.rest.memserver;
{ ************ ORM and SOA Logic Extraction from RTTI }
/// compute the Model information, ready to be exported as JSON
// - will publish the ORM and SOA properties
// - to be used e.g. for client code generation via Mustache templates
// - optional aSourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit - this text content may
// also be injected by WRAPPER_RESOURCENAME
// - you may specify a description file (as generated by FillDescriptionFromSource)
function ContextFromModel(aServer: TRestServer;
const aSourcePath: TFileName = '';
const aDescriptions: TFileName = ''): variant;
/// compute the SOA information, ready to be exported as JSON
// - will publish the ORM and SOA properties
// - to be used e.g. for client code generation via Mustache templates
function ContextFromUsedInterfaces(const aSourcePath: TFileName = '';
const aDescriptions: TFileName = ''): variant;
/// compute the information of an interface method, ready to be exported as JSON
// - to be used e.g. for the implementation of the MVC controller via interfaces
// - no description text will be included - use ContextFromModel() if needed
function ContextFromMethod(const method: TInterfaceMethod): variant;
/// compute the information of an interface, ready to be exported as JSON
// - to be used e.g. for the implementation of the MVC controller via interfaces
// - no description text will be included - use ContextFromModel() if needed
function ContextFromMethods(int: TInterfaceFactory): variant;
{ ************ Doc/CodeGen wrapper Functions on Server Side }
/// generate a code/doc wrapper for a given Model and Mustache template content
// - will use all ORM and SOA properties of the supplied server
// - aFileName will be transmitted as {{filename}}, e.g. 'mORMotClient'
// - you should also specify a "fake" HTTP port e.g. 888
// - the template content could be retrieved from a file via StringFromFile()
// - you may optionally retrieve a copy of the data context as TDocVariant
// - this function may be used to generate the client at build time, directly
// from a just built server, in an automated manner
// - you may specify custom helpers (e.g. via TSynMustache.HelpersGetStandardList)
// and retrieve the generated data context after generation (if aContext is
// a TDocVariant object, its fields would be added to the rendering context),
// or a custom description file (as generated by FillDescriptionFromSource)
function WrapperFromModel(aServer: TRestServer;
const aMustacheTemplate, aFileName: RawUtf8; aPort: integer;
aHelpers: TSynMustacheHelpers = nil;
aContext: PVariant = nil;
const aDescriptions: TFileName = ''): RawUtf8;
/// generate a code/doc wrapper for a given set of types and Mustache template content
// - will use aTables[] to define the ORM information, and supplied aSharedServices[]
// aSharedServicesContract[] for SOA definition of a shared API (expected to
// be called from TRestClientUri.ServiceDefineSharedApi)
// - aFileName will be transmitted as {{filename}}, e.g. 'mORMotClient'
// - you should also specify a "fake" HTTP port e.g. 888
// - the template content could be retrieved from a file via StringFromFile()
// - you may optionally retrieve a copy of the data context as TDocVariant
// - this function may be used to generate the client at build time, directly
// from a just built server, in an automated manner
// - you may specify custom helpers (e.g. via TSynMustache.HelpersGetStandardList)
// and retrieve the generated data context after generation (if aContext is
// a TDocVariant object, its fields would be added to the rendering context),
// or a custom description file (as generated by FillDescriptionFromSource)
function WrapperForPublicAPI(const aTables: array of TOrmClass;
const aRoot, aMustacheTemplate, aFileName: RawUtf8;
const aSharedServices: array of TGuid;
const aSharedServicesContract: array of RawUtf8;
aResultAsJsonObjectWithoutResult: boolean; aPort: integer;
aHelpers: TSynMustacheHelpers = nil; aContext: PVariant = nil;
const aDescriptions: TFileName = ''): RawUtf8;
/// instantiate a TRest server instance, including supplied ORM and SOA definitions
// - will use aTables[] to define the ORM information, and supplied aSharedServices[]
// aSharedServicesContract[] for SOA definition of a shared API, implemented as
// abstract classes using TInterfaceStub
// - as used e.g. by WrapperForPublicAPI() to generate some code/doc wrappers
function WrapperFakeServer(const aTables: array of TOrmClass;
const aRoot: RawUtf8;
const aSharedServices: array of TGuid;
const aSharedServicesContract: array of RawUtf8;
aResultAsJsonObjectWithoutResult: boolean): TRestServerFullMemory;
/// you can call this procedure within a method-based service allow
// code-generation of an ORM and SOA client from a web browser
// - you have to specify one or several client *.mustache file paths
// - the first path containing any *.mustache file will be used as templates
// - for instance:
// ! procedure TCustomServer.Wrapper(Ctxt: TRestServerUriContext);
// ! begin // search in the current path
// ! WrapperMethod(Ctxt,['.']);
// ! end;
// - optional SourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit
// - you may specify a description file (as generated by FillDescriptionFromSource)
procedure WrapperMethod(Ctxt: TRestServerUriContext;
const Path: array of TFileName;
const SourcePath: TFileName = '';
const Descriptions: TFileName = '');
/// you can call this procedure to add a 'Wrapper' method-based service
// to a given server, to allow code-generation of an ORM and SOA client
// - you have to specify one or several client *.mustache file paths
// - the first path containing any *.mustache file will be used as templates
// - if no path is specified (i.e. as []), it will search in the .exe folder
// - the root/wrapper URI will be accessible without authentication (i.e.
// from any plain browser)
// - for instance:
// ! aServer := TRestServerFullMemory.Create(aModel,'test.json',false,true);
// ! AddToServerWrapperMethod(aServer,['..']);
// - optional SourcePath parameter may be used to retrieve additional description
// from the comments of the source code of the unit
procedure AddToServerWrapperMethod(Server: TRestServer;
const Path: array of TFileName;
const SourcePath: TFileName = '');
{ ************ Documentation Extraction from Source Code Comments }
/// rough parsing of the supplied .pas unit, adding the /// commentaries
// into a TDocVariant content
procedure FillDescriptionFromSource(var Descriptions: TDocVariantData;
const SourceFileName: TFileName);
/// rough parsing of the supplied .pas unit, adding the /// commentaries
// into a compressed binary resource
// - could be then compiled into a WRAPPER_RESOURCENAME resource, e.g. via the
// following .rc source file, assuming ResourceDestFileName='wrapper.desc':
// $ WrappersDescription 10 "wrapper.desc"
// - you may specify a .json file name, for debugging/validation purposes
// - calls internally FillDescriptionFromSource
// - returns the TDocVariant JSON object corresponding to all decriptions
function ResourceDescriptionFromSource(const ResourceDestFileName: TFileName;
const SourceFileNames: array of TFileName;
const JsonDestFileName: TFileName = ''): variant;
const
/// internal Resource name used for bounded description
// - as generated by FillDescriptionFromSource/ResourceDescriptionFromSource
// - would be used e.g. by TWrapperContext.Create to inject the available
// text description from any matching resource
WRAPPER_RESOURCENAME = 'WrappersDescription';
var
/// how FillDescriptionFromSource() handles trailing '-' in parsed comments
// - default is [*], as expected by buggy AsciiDoc format
DESCRIPTION_ITEM_PREFIX: RawUtf8 = ' [*]';
{ ************ FPC Dedicated Generators }
/// you can call this procedure to generate the mORMotServer.pas unit needed
// to compile a given server source code using FPC
// - will locate FPCServer-mORMotServer.pas.mustache in the given Path[] array
// - will write the unit using specified file name or to mORMotServer.pas in the
// current directory if DestFileName is '', or to a sub-folder of the matching
// Path[] if DestFileName starts with '\' (to allow relative folder use)
// - the missing RTTI for records and interfaces would be defined, together
// with some patch comments for published record support (if any) for the ORM
procedure ComputeFPCServerUnit(Server: TRestServer; const
Path: array of TFileName;
DestFileName: TFileName = '');
/// you can call this procedure to generate the mORMotInterfaces.pas unit needed
// to register all needed interface RTTI for FPC
// - to circumvent http://bugs.freepascal.org/view.php?id=26774 unresolved issue
// - will locate FPC-mORMotInterfaces.pas.mustache in the given Path[] array
// - will write the unit using specified file name or to mORMotInterfaces.pas in
// the current directory if DestFileName is '', or to a sub-folder of the
// matching Path[] if DestFileName starts with '\' (to allow relative folder use)
// - all used interfaces will be exported, including SOA and mocking/stubing
// types: so you may have to run this function AFTER all process is done
procedure ComputeFPCInterfacesUnit(const Path: array of TFileName;
DestFileName: TFileName = '');
{ ************ Compute Asynchronous Code from Synchronous Interface }
/// this function would generate a pascal unit defining asynchronous
// (non-blocking) types from a DDD's blocking dual-phase Select/Command service
// - you should specify the services to be converted, as an array - note that
// due to how RTTI is stored by the compiler, all "pure input" parameters should
// be defined explicitly as "const", otherwise the generated class won't match
// - optionally, the TCQRSServiceClass implementing the first Select() phase of
// the blocking service may be specified in queries array; a set of unit names
// in which those TCQRSServiceClass are defined may be specified
// - a Mustache template content should be provided - e.g. asynch.pas.mustache
// as published in SQLite3\DDD\dom folder of the source code repository
// - FileName would contain the resulting unit filename (without the .pas)
// - ProjectName would be written in the main unit comment
// - CallType should be the type used at Domain level to identify each
// asynchronous call - this type should be an integer, or a function may be
// supplied as CallFunction (matching VariantToInteger signature)
// - the first phase of the service should have set Key: KeyType, which would be
// used to create a single shared asynchronous service instance for all keys
// - ExceptionType may be customize, mainly to use a Domain-specific class
// - blocking execution may reach some timeout waiting for the asynchronous
// acknowledgement: a default delay (in ms) is to be supplied, and some custom
// delays may be specified as trios, e.g. ['IMyInterface', 'Method', 10000, ...]
function GenerateAsynchServices(const services: array of TGuid;
const queries: array of TClass;
const units: array of const;
const additionalcontext: array of const;
Template, FileName, ProjectName, CallType, CallFunction,
Key, KeyType, ExceptionType: RawUtf8;
DefaultDelay: integer; const CustomDelays: array of const): RawUtf8;
{ ************ Generate Code and Doc from Command-Line }
type
/// the options retrieved during a ExecuteFromCommandLine() call
TServiceClientCommandLineOptions = set of (
cloPrompt,
cloNoColor,
cloPipe,
cloHeaders,
cloVerbose,
cloNoExpand,
cloNoBody);
/// event handler to let ExecuteFromCommandLine call a remote server
// - before call, aParams.InBody will be set with the expected JSON content
TOnCommandLineCall = procedure(aOptions: TServiceClientCommandLineOptions;
const aService: TInterfaceFactory; aMethod: PInterfaceMethod;
var aParams: TRestUriParams) of object;
const
/// help information displayed by ExecuteFromCommandLine() with no command
// - note that Windows and POSIX don't handle the double quotes similarly,
// so putting JSON on the command line could be tricky and needs ' escaping
EXECUTEFROMCOMMANDLINEHELP =
' % help -> show all services (interfaces)'#13#10 +
' % [service] [help] -> show all methods of a given service'#13#10 +
' % [service] [method] help -> show parameters of a given method'#13#10 +
' % [options] [service] [method] [parameters] -> call a given method ' +
{$ifdef OSWINDOWS}
'with [parameters] being name=value or name=""value with spaces"" or ' +
'name:={""some"":""json""}' +
' and [options] as /nocolor /pipe /headers /verbose /noexpand /nobody';
{$else}
'with [parameters] being name=value or name=''"value with spaces"'' or ' +
'name:=''{"some":"json"}''' +
' and [options] as --nocolor --pipe --headers --verbose --noexpand --nobody';
{$endif OSWINDOWS}
/// command-line SOA remote access to mORMot interface-based services
// - supports the EXECUTEFROMCOMMANDLINEHELP commands
// - you shall have registered the aServices interface(s) by a previous call to
// the overloaded Get(TypeInfo(IMyInterface)) method or RegisterInterfaces()
// - you may specify an optional description file, as previously generated
// by mormot.soa.codegen.pas' FillDescriptionFromSource function - a local
// 'WrappersDescription' resource will also be checked
// - to actually call the remote server, aOnCall should be supplied
procedure ExecuteFromCommandLine(
const aServices: array of TGuid;
const aOnCall: TOnCommandLineCall;
const aDescriptions: TFileName = '');
implementation
{ ************ ORM and SOA Logic Extraction from RTTI }
type
/// a cross-platform published property kind
// - does not match mormot.orm.core.pas TOrmFieldType: here we recognize only
// types which may expect a special behavior in SynCrossPlatformREST.pas unit
// - should match TOrmFieldKind order in SynCrossPlatformREST.pas
TCrossPlatformOrmFieldKind = (
cpkDefault,
cpkDateTime,
cpkTimeLog,
cpkBlob,
cpkModTime,
cpkCreateTime,
cpkRecord,
cpkVariant);
const
/// those text values should match TOrmFieldKind in SynCrossPlatformREST.pas
// - was previously named sft* in mORMot 1.18
CROSSPLATFORMKIND_TEXT: array[TCrossPlatformOrmFieldKind] of RawUtf8 = (
'oftUnspecified',
'oftDateTime',
'oftTimeLog',
'oftBlob',
'oftModTime',
'oftCreateTime',
'oftRecord',
'oftVariant');
type
/// types recognized and handled by this mormot.soa.codegen.pas unit
TWrapperType = (
wUnknown,
wBoolean,
wEnum,
wSet,
wByte,
wWord,
wInteger,
wCardinal,
wInt64,
wQWord,
wID,
wReference,
wTimeLog,
wModTime,
wCreateTime,
wCurrency,
wSingle,
wDouble,
wDateTime,
wRawUtf8,
wString,
wRawJson,
wBlob,
wGuid,
wCustomAnswer,
wRecord,
wArray,
wVariant,
wObject,
wORM, // was wSQLRecord
wInterface,
wRecordVersion);
/// supported languages typesets
TWrapperLanguage = (
lngDelphi,
lngPascal,
lngCS,
lngJava,
lngTypeScript,
lngSwagger);
const
CROSSPLATFORM_KIND: array[TOrmFieldType] of TCrossPlatformOrmFieldKind =(
cpkDefault, // oftUnknown
cpkDefault, // oftAnsiText
cpkDefault, // oftUtf8Text
cpkDefault, // oftEnumerate
cpkDefault, // oftSet
cpkDefault, // oftInteger
cpkDefault, // oftID
cpkDefault, // oftRecord
cpkDefault, // oftBoolean
cpkDefault, // oftFloat
cpkDateTime, // oftDateTime
cpkTimeLog, // oftTimeLog
cpkDefault, // oftCurrency
cpkDefault, // oftObject
cpkVariant, // oftVariant
cpkVariant, // oftNullable
cpkBlob, // oftBlob
cpkDefault, // oftBlobDynArray
cpkDefault, // oftBlobCustom
cpkRecord, // oftUtf8Custom
cpkDefault, // oftMany
cpkModTime, // oftModTime
cpkCreateTime, // oftCreateTime
cpkDefault, // oftTID
cpkDefault, // oftRecordVersion
cpkDefault, // oftSessionUserID
cpkDateTime, // oftDateTimeMS
cpkDefault, // oftUnixTime
cpkDefault); // oftUnixMSTime
SIZETODELPHI: array[0..8] of string[7] = (
'integer', 'byte', 'word', 'integer',
'integer', 'int64', 'int64', 'int64', 'int64');
TYPES_SIZE: array[0..8] of TWrapperType = (
wInteger, wByte, wWord, wInteger,
wInteger, wInt64, wInt64, wInt64, wInt64);
// Swagger numerical types
SWI32 = '{"type":"integer"}';
SWI64 = '{"type":"integer","format":"int64"}';
SWD32 = '{"type":"number","format":"float"}';
SWD64 = '{"type":"number","format":"double"}';
{ TODO: refactor TID and Int64 for JavaScript? (integers truncated to 53-bit) }
TYPES_LANG: array[TWrapperLanguage, TWrapperType] of RawUtf8 = (
// lngDelphi
('', 'Boolean', '', '', 'Byte', 'Word', 'Integer', 'Cardinal', 'Int64',
'UInt64', 'TID', 'TRecordReference', 'TTimeLog', 'TModTime', 'TCreateTime',
'Currency', 'Single', 'Double', 'TDateTime', 'RawUtf8', 'String', 'RawJson',
'RawBlob', 'TGuid', 'TServiceCustomAnswer', '', '', 'Variant', '', '', '',
'TRecordVersion'),
// lngPascal
('', 'Boolean', '', '', 'Byte', 'Word', 'Integer', 'Cardinal', 'Int64',
'UInt64', 'TID', 'TRecordReference', 'TTimeLog', 'TModTime', 'TCreateTime',
'Currency', 'Single', 'Double', 'TDateTime', 'String', 'String', 'Variant',
'RawBlob', 'TGuid', 'THttpBody', '', '', 'Variant', '', 'TID', '', 'TRecordVersion'),
// lngCS
('', 'bool', '', '', 'byte', 'word', 'integer', 'uint', 'long', 'ulong',
'TID', 'TRecordReference', 'TTimeLog', 'TModTime', 'TCreateTime', 'decimal',
'single', 'double', 'double', 'string', 'string', 'dynamic', 'byte[]',
'Guid', 'byte[]', '', '', 'dynamic', '', 'TID', '', 'TRecordVersion'),
// lngJava
('', 'boolean', '', '', 'byte', 'int', 'int', 'long', 'long', 'long', 'TID',
'TRecordReference', 'TTimeLog', 'TModTime', 'TCreateTime', 'BigDecimal',
'single', 'double', 'double', 'String', 'String', 'Object', 'byte[]',
'String', 'byte[]', '', '', 'Object', '', 'TID', '', 'TRecordVersion'),
// lngTypeScript
('', 'boolean', '', '', 'number', 'number', 'number', 'number', 'number',
'number', 'mORMot.TID', 'mORMot.TRecordReference', 'mORMot.TTimeLog',
'mORMot.TModTime', 'mORMot.TCreateTime', 'number', 'number', 'number',
'mORMot.TDateTime', 'string', 'string', 'any', 'mORMot.RawBlob',
'mORMot.TGuid', 'mORMot.THttpBody', '', '', 'any', '', '', '',
'mORMot.TRecordVersion'),
// lngSwagger
('', '{"type":"boolean"}', '', '', SWI32, SWI32, SWI32, SWI32, SWI64, SWI64,
SWI64, SWI64, SWI64, SWI64, SWI64, SWD64, SWD32, SWD64,
'{"type":"string","format":"date-time"}', // wDateTime
'{"type":"string"}', '{"type":"string"}', '{"type":"object"}', //FIXME! //wRawJson
'{"type":"string","format":"binary"}', '{"type":"string"}', //wBlob,wGuid
'', '', '', '', //wCustomAnswer, wRecord, wArray, wVariant
'', SWI64, '', '' //wObject, wORM, wInterface, wRecordVersion
));
TYPES_ORM: array[TOrmFieldType] of TWrapperType = (
wUnknown, // oftUnknown
wString, // oftAnsiText
wRawUtf8, // oftUtf8Text
wEnum, // oftEnumerate
wSet, // oftSet
wUnknown, // oftInteger - wUnknown to force exact type
wORM, // oftID
wReference, // oftRecord
wBoolean, // oftBoolean
wUnknown, // oftFloat - wUnknown to force exact type
wDateTime, // oftDateTime
wTimeLog, // oftTimeLog
wCurrency, // oftCurrency
wObject, // oftObject
wVariant, // oftVariant
wVariant, // oftNullable
wBlob, // oftBlob
wArray, // oftBlobDynArray - with specific code below
wRecord, // oftBlobCustom
wRecord, // oftUtf8Custom
wUnknown, // oftMany
wModTime, // oftModTime
wCreateTime, // oftCreateTime
wID, // oftID
wRecordVersion, // oftRecordVersion
wID, // oftSessionUserID
wDateTime, // oftDateTimeMS
wUnknown, // oftUnixTime
wUnknown); // oftUnixMSTime
TYPES_SIMPLE: array[TRttiParserType] of TWrapperType = (
wUnknown, // ptNone
wArray, // ptArray
wBoolean, // ptBoolean
wByte, // ptByte
wCardinal, // ptCardinal
wCurrency, // ptCurrency
wDouble, // ptDouble
wDouble, // ptExtended
wInt64, // ptInt64
wInteger, // ptInteger
wQWord, // ptQWord
wBlob, // ptRawByteString
wRawJson, // ptRawJson
wRawUtf8, // ptRawUtf8
wRecord, // ptRecord
wSingle, // ptSingle
wString, // ptString
wRawUtf8, // ptSynUnicode
wDateTime, // ptDateTime
wDateTime, // ptDateTimeMS
wGuid, // ptGuid
wBlob, // ptHash128
wBlob, // ptHash256
wBlob, // ptHash512
wID, // ptOrm
wTimeLog, // ptTimeLog
wRawUtf8, // ptUnicodeString
wInt64, // ptUnixTime
wInt64, // ptUnixMSTime
wVariant, // ptVariant
wRawUtf8, // ptWideString
wRawUtf8, // ptWinAnsi
wWord, // ptWord
wEnum, // ptEnumeration
wSet, // ptSet
wUnknown, // ptClass
wArray, // ptDynArray - with specific code below
wUnknown, // ptInterface
wRawUtf8, // ptPUtf8Char
wUnknown); // ptCustom
TYPES_SOA: array[TInterfaceMethodValueType] of TWrapperType = (
wUnknown, // imvNone
wUnknown, // imvSelf
wBoolean, // imvBoolean
wEnum, // imvEnum
wSet, // imvSet
wUnknown, // imvInteger
wUnknown, // imvCardinal
wUnknown, // imvInt64
wDouble, // imvDouble
wDateTime, // imvDateTime
wCurrency, // imvCurrency
wRawUtf8, // imvRawUtf8
wString, // imvString
wRawUtf8, // imvRawByteString
wRawUtf8, // imvWideString
wRecord, // imvRecord
wVariant, // imvVariant
wObject, // imvObject
wRawJson, // imvRawJson
wArray, // imvDynArray
wUnknown); // imvInterface
// integers are wUnknown to force best type recognition
type
EWrapperContext = class(ESynException);
/// this non-published class is used internally to extract info from RTTI
TWrapperContext = class
protected
fServer: TRestServer;
fORM, fRecords, fEnumerates, fSets, fArrays: TDocVariantData;
fUnits, fDescriptions: TDocVariantData;
fSOA: variant;
fSourcePath: TFileNameDynArray;
fHasAnyRecord: boolean;
fNestedId: integer; // for unique nested type names if no RTTI
function ContextFromRtti(typ: TWrapperType; rtti: TRttiCustom = nil;
typName: RawUtf8 = ''; const parentName: RawUtf8 = ''): variant;
function ContextNestedProperties(rtti: TRttiCustom;
const parentName: RawUtf8): variant;
function ContextOneProperty(const prop: TRttiCustomProp;
const parentName: RawUtf8): variant;
function ContextFromMethods(int: TInterfaceFactory): variant;
function ContextFromMethod(const meth: TInterfaceMethod): variant;
function ContextArgsFromMethod(const meth: TInterfaceMethod): variant;
procedure AddUnit(const aUnitName: ShortString; addAsProperty: PVariant);
public
constructor Create(const aSourcePath, aDescriptions: TFileName);
constructor CreateFromModel(aServer: TRestServer;
const aSourcePath: TFileName; const aDescriptions: TFileName);
constructor CreateFromUsedInterfaces(
const aSourcePath, aDescriptions: TFileName);
function Context: variant;
end;
{ TWrapperContext }
constructor TWrapperContext.Create(const aSourcePath, aDescriptions: TFileName);
var
desc: RawByteString;
source: TFileName;
src: PChar;
n: PtrInt;
begin
TDocVariant.NewFast([
@fORM,
@fRecords,
@fEnumerates,
@fSets,
@fArrays,
@fUnits,
@fDescriptions]);
if aDescriptions <> '' then
desc := StringFromFile(aDescriptions);
if {%H-}desc = '' then
ResourceSynLZToRawByteString(WRAPPER_RESOURCENAME, desc);
if desc <> '' then
fDescriptions.InitJsonInPlace(pointer(desc), JSON_FAST);
if aSourcePath <> '' then
begin
src := pointer(aSourcePath);
n := 0;
repeat
source := GetNextItemString(src, ';');
if (source <> '') and
DirectoryExists(source) then
begin
SetLength(fSourcePath, n + 1);
fSourcePath[n] := IncludeTrailingPathDelimiter(source);
inc(n);
end;
until src = nil;
end;
end;
function TWrapperContext.ContextNestedProperties(rtti: TRttiCustom;
const parentName: RawUtf8): variant;
var
i: PtrInt;
begin
SetVariantNull(result);
case rtti.Parser of
ptRecord,
ptClass:
; // use rtti.Props
ptArray,
ptDynArray:
rtti := rtti.ArrayRtti; // use array item
else
exit; // no nested properties
end;
TDocVariant.NewFast(result);
for i := 0 to rtti.Props.Count - 1 do
TDocVariantData(result).AddItem(
ContextOneProperty(rtti.Props.List[i], parentName));
end;
function ClassToWrapperType(c: TClass): TWrapperType;
begin
if c.InheritsFrom(TOrm) then
result := wORM
else
result := wObject;
end;
function TWrapperContext.ContextFromRtti(typ: TWrapperType; rtti: TRttiCustom;
typName: RawUtf8; const parentName: RawUtf8): variant;
var
typAsName: PShortString;
function VarName(lng: TWrapperLanguage): variant;
begin
if TYPES_LANG[lng, typ] <> '' then
RawUtf8ToVariant(TYPES_LANG[lng, typ], result)
else if typName = '' then
SetVariantNull(result)
else
RawUtf8ToVariant(typName, result);
end;
function VarSwagger: variant;
begin
if TYPES_LANG[lngSwagger, typ] <> '' then
result := _JsonFast(TYPES_LANG[lngSwagger, typ])
else if typName = '' then
SetVariantNull(result)
else
RawUtf8ToVariant(typName, result);
end;
procedure RegisterType(var list: TDocVariantData);
var
info: variant;
begin
if list.SearchItemByProp('name', typName, false) >= 0 then
// already registered
exit;
if rtti = nil then
EWrapperContext.RaiseUtf8('%.RegisterType(%): no RTTI', [typAsName^, typName]);
case typ of
wEnum,
wSet:
// include (untrimed) identifier: values[] may be trimmed at mustache level
info := _JsonFastFmt('{name:?,values:%}',
[rtti.Cache.EnumInfo^.GetEnumNameAllAsJsonArray(false)], [typName]);
wRecord:
if rtti.Props.Count <> 0 then
info := _ObjFast([
'name', typName,
'camelName', LowerCamelCase(typName),
'snakeName', SnakeCase(typName),
'fields', ContextNestedProperties(rtti, parentName)]);
wArray:
begin
if rtti.ObjArrayClass <> nil then
begin
info := ContextFromRtti(
ClassToWrapperType(rtti.ObjArrayClass), rtti.ArrayRtti);
_Safe(info)^.AddValue('isObjArray', true);
end
else
begin
if rtti.ArrayRtti = nil then
if rtti.Cache.ItemSize > high(TYPES_SIZE) then
// to avoid buffer overflow
info := ContextFromRtti(wRawUtf8)
else
info := ContextFromRtti(TYPES_SIZE[rtti.Cache.ItemSize])
else if rcfBinary in rtti.ArrayRtti.Flags then
info := ContextFromRtti(wRawUtf8)
else
info := ContextFromRtti(wUnknown, rtti.ArrayRtti);
end;
// can be used to create static array (dynamic arrays have ItemCount=0)
// array{{#staticMaxIndex}}[0..{{staticMaxIndex}}]{{/staticMaxIndex}} of
_ObjAddProps([
'name', typName,
'camelName', LowerCamelCase(typName),
'snakeName', SnakeCase(typName)], info);
if rtti.Cache.ItemCount > 0 then
_Safe(info)^.AddValue('staticMaxIndex', rtti.Cache.ItemCount-1);
end;
end;
if not VarIsEmptyOrNull(info) then
// null e.g. for a record without custom text definition
list.AddItem(info);
end;
begin
// retrieve typ from RTTI if needed
if typ = wUnknown then
begin
if rtti = nil then
EWrapperContext.RaiseUtf8(
'%.ContextFromRtti: No RTTI nor typ for [%]', [self, typName]);
typ := TYPES_ORM[GetOrmFieldType(rtti.Info)];
if typ = wUnknown then
begin
typ := TYPES_SIMPLE[rtti.Parser];
if typ = wUnknown then
case rtti.Kind of
{$ifdef FPC}rkObject,{$else}{$ifdef UNICODE}rkMRecord,{$endif}{$endif}
rkRecord:
typ := wRecord;
rkInterface:
typ := wInterface;
else
EWrapperContext.RaiseUtf8(
'%.ContextFromRtti: Not enough RTTI for [%]', [self, rtti.Name]);
end;
end;
end;
if (typ = wRecord) and
PropNameEquals(typName, 'TGUID') then
typ := wGuid
else if (typ = wRecord) and
PropNameEquals(typName, 'TServiceCustomAnswer') then
typ := wCustomAnswer;
// set typName/typAsName
if typName = '' then
if rtti <> nil then
if rcfWithoutRtti in rtti.Flags then // undefined nested fields
FormatUtf8('T%%', [parentName, InterlockedIncrement(fNestedId)], typName)
else
typName := rtti.Name
else
typName := TYPES_LANG[lngDelphi, typ];
typAsName := GetEnumName(TypeInfo(TWrapperType), ord(typ));
// generate basic context as TDocVariant fields
result := _ObjFast([
'typeWrapper', typAsName^,
'typeSource', typName,
'typeDelphi', VarName(lngDelphi),
'typePascal', VarName(lngPascal),
'typeCS', VarName(lngCS),
'typeJava', VarName(lngJava),
'typeTS', VarName(lngTypeScript),
'typeSwagger', VarSwagger]);
if self = nil then
// no need to have full info if called e.g. from MVC
exit;
// add special marshalling information
if rtti <> nil then
case rtti.Kind of
rkClass:
AddUnit(rtti.Info^.RttiClass^.UnitName^, @result);
end;
case typ of
wBoolean,
wByte,
wWord,
wInteger,
wCardinal,
wInt64,
wQWord,
wID,
wReference,
wTimeLog,
wModTime,
wCreateTime,
wSingle,
wDouble,
wRawUtf8,
wString:
; // simple types have no special marshalling
wDateTime:
_ObjAddProps(['isDateTime', true,
'toVariant', 'DateTimeToIso8601',
'fromVariant', 'Iso8601ToDateTime'], result);
wRecordVersion:
_ObjAddProp('isRecordVersion', true, result);
wCurrency:
_ObjAddProp('isCurrency', true, result);
wVariant:
_ObjAddProp('isVariant', true, result);
wRawJson:
_ObjAddProp('isJson', true, result);
wEnum:
begin
_ObjAddProps(['isEnum', true,
'toVariant', 'ord',
'fromVariant', 'Variant2' + typName], result);
if self <> nil then
RegisterType(fEnumerates);
end;
wSet:
begin
_ObjAddProps(['isSet', true,
'toVariant',
SIZETODELPHI[rtti.Cache.EnumInfo.SizeInStorageAsSet],
'fromVariant', typName], result);
if self <> nil then
RegisterType(fSets);
end;
wGuid:
_ObjAddProps(['toVariant', 'GuidToVariant',
'fromVariant', 'VariantToGuid'], result);
wCustomAnswer:
_ObjAddProps(['toVariant', 'HttpBodyToVariant',
'fromVariant', 'VariantToHttpBody'], result);
wRecord:
begin
_ObjAddProp('isRecord', true, result);
if rtti <> nil then
begin
_ObjAddProps(['toVariant', typName + '2Variant',
'fromVariant', 'Variant2' + typName], result);
if self <> nil then
RegisterType(fRecords);
end;
end;
wOrm:
if (fServer <> nil) and
(fServer.Model.GetTableIndexInheritsFrom(
TOrmClass(rtti.ValueClass)) < 0) then
EWrapperContext.RaiseUtf8(
'%.ContextFromRtti: % should be part of the model', [self, typName])
else
_ObjAddProps(['isSQLRecord', true,
'isOrm', true], result);
wObject:
begin
_ObjAddProp('isObject', true, result);
if rtti <> nil then
_ObjAddProps(['toVariant', 'ObjectToVariant',
'fromVariant', typName + '.CreateFromVariant'], result);
end;
wArray:
begin
_ObjAddProp('isArray', true, result);
if rtti <> nil then
begin
_ObjAddProps(['toVariant', typName + '2Variant',
'fromVariant', 'Variant2' + typName], result);
if self <> nil then
RegisterType(fArrays);
end;
end;
wBlob:
_ObjAddProps(['isBlob', true,
'toVariant', 'BlobToVariant',
'fromVariant', 'VariantToBlob'], result);
wInterface:
_ObjAddProp('isInterface', true, result);
else
EWrapperContext.RaiseUtf8(
'Unexpected type % (%) for [%]', [typAsName^, ord(typ), typName]);
end;
end;
constructor TWrapperContext.CreateFromModel(aServer: TRestServer;
const aSourcePath, aDescriptions: TFileName);
var
t, f, s: PtrInt;
nfoList: TOrmPropInfoList;
nfo: TOrmPropInfo;
nfoOrmFieldRttiTypeName: RawUtf8;
kind: TCrossPlatformOrmFieldKind;
hasRecord: boolean;
fields, services: TDocVariantData;
field, rec: variant;
srv: TServiceFactoryServer;
uri: RawUtf8;
begin
Create(aSourcePath, aDescriptions);
fServer := aServer;
TDocVariant.NewFast([
@fields,
@services]);
// compute ORM information
for t := 0 to fServer.Model.TablesMax do
begin
nfoList := fServer.Model.TableProps[t].Props.Fields;
fields.Clear;
fields.Init;
hasRecord := false;
for f := 0 to nfoList.Count - 1 do
begin
nfo := nfoList.List[f];
nfoOrmFieldRttiTypeName := nfo.SqlFieldRttiTypeName;
if nfo.InheritsFrom(TOrmPropInfoRtti) then
field := ContextFromRtti(TYPES_ORM[nfo.OrmFieldType],
TOrmPropInfoRtti(nfo).PropRtti, nfoOrmFieldRttiTypeName)
else if nfo.InheritsFrom(TOrmPropInfoRecordTyped) then
begin
hasRecord := true;
fHasAnyRecord := true;
field := ContextFromRtti(wRecord,
Rtti.RegisterType(TOrmPropInfoRecordTyped(nfo).TypeInfo),
nfoOrmFieldRttiTypeName);
end
else
EWrapperContext.RaiseUtf8('Unexpected type % for %.%',
[nfo, fServer.Model.Tables[t], nfo.Name]);
kind := CROSSPLATFORM_KIND[nfo.OrmFieldType];
_ObjAddProps(['index', f + 1,
'name', nfo.Name,
'camelName', LowerCamelCase(nfo.Name),
'snakeName', SnakeCase(nfo.Name),
'sql', ord(nfo.OrmFieldType),
'sqlName', nfo.OrmFieldTypeName^,
'typeKind', ord(kind),
'typeKindName', CROSSPLATFORMKIND_TEXT[kind],
'attr', byte(nfo.Attributes)], field);
if aIsUnique in nfo.Attributes then
_ObjAddProp('unique', true, field);
if nfo.FieldWidth > 0 then
_ObjAddProp('width', nfo.FieldWidth, field);
if f < nfoList.Count - 1 then
_ObjAddPropU('comma', ',', field)
else
// may conflict with rec.comma otherwise
_ObjAddProp('comma', null, field);
fields.AddItem(field);
end;
with fServer.Model.TableProps[t] do
rec := _JsonFastFmt('{tableName:?,className:?,classParent:?,' +
'fields:?,isInMormotPas:%,unitName:?,comma:%}',
[NULL_OR_TRUE[(Props.Table = TAuthGroup) or
(Props.Table = TAuthUser)],
NULL_OR_COMMA[t < fServer.Model.TablesMax]],
[Props.SqlTableName, ClassNameShort(Props.Table)^,
ClassNameShort(Props.Table.ClassParent)^,
Variant(fields),
Props.TableRtti.Info.RttiClass^.UnitName]);
if hasRecord then
rec.hasRecords := true;
fORM.AddItem(rec);
end;