-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuRestPoolerDB.pas
2439 lines (2317 loc) · 83.2 KB
/
uRestPoolerDB.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
{
Esse pacote de Componentes foi desenhado com o Objetivo de ajudar as pessoas a desenvolverem
com WebServices REST o mais próximo possível do desenvolvimento local DB, com componentes de
fácil configuração para que todos tenham acesso as maravilhas dos WebServices REST/JSON DataSnap.
Desenvolvedor Principal : Gilberto Rocha da Silva (XyberX)
Empresa : XyberPower Desenvolvimento
}
unit uRestPoolerDB;
interface
uses System.SysUtils, System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Stan.Async,
FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Comp.Client, FireDAC.Comp.UI,
FireDAC.Comp.DataSet, FireDAC.DApt.Intf, Data.DBXJSON,
Data.DB, Data.FireDACJSONReflect, Data.DBXJSONReflect,
IPPeerClient, Datasnap.DSClientRest, System.SyncObjs,
uPoolerMethod, Data.DBXPlatform
{$IFDEF MSWINDOWS}, Datasnap.DSServer,
Datasnap.DSAuth, Datasnap.DSProxyRest {$ENDIF},
Soap.EncdDecd, uMasterDetailData,
DbxCompressionFilter, uRestCompressTools, System.ZLib,
uPoolerServerMethods
{$if CompilerVersion >= 28}
,System.NetEncoding, System.JSON, FireDAC.Stan.StorageJSON, FireDAC.Stan.StorageBin
{$endif};
Type
TEncodeSelect = (esASCII, esUtf8);
TOnEventDB = Procedure (DataSet : TDataSet) of Object;
TOnAfterScroll = Procedure (DataSet : TDataSet) of Object;
TOnAfterOpen = Procedure (DataSet : TDataSet) of Object;
TOnAfterClose = Procedure (DataSet : TDataSet) of Object;
TOnAfterInsert = Procedure (DataSet : TDataSet) of Object;
TOnBeforeDelete = Procedure (DataSet : TDataSet) of Object;
TOnBeforePost = Procedure (DataSet : TDataSet) of Object;
TOnAfterPost = Procedure (DataSet : TDataSet) of Object;
TExecuteProc = Reference to Procedure;
TOnEventConnection = Procedure (Sucess : Boolean;
Const Error : String) of Object;
TOnEventBeforeConnection = Procedure (Sender : TComponent) of Object;
TOnEventTimer = Procedure of Object;
TBeforeGetRecords = Procedure (Sender : TObject;
Var OwnerData : OleVariant) of Object;
Type
TTimerData = Class(TThread)
Private
FValue : Integer; //Milisegundos para execução
FLock : TCriticalSection; //Seção crítica
vEvent : TOnEventTimer; //Evento a ser executado
Public
Property OnEventTimer : TOnEventTimer Read vEvent Write vEvent; //Evento a ser executado
Protected
Constructor Create(AValue: Integer; ALock: TCriticalSection); //Construtor do Evento
Procedure Execute; Override; //Procedure de Execução automática
End;
Type
TAutoCheckData = Class(TPersistent)
Private
vAutoCheck : Boolean; //Se tem Autochecagem
vInTime : Integer; //Em milisegundos o timer
Timer : TTimerData; //Thread do temporizador
vEvent : TOnEventTimer; //Evento a executar
FLock : TCriticalSection; //CriticalSection para execução segura
Procedure SetState(Value : Boolean); //Ativa ou desativa a classe
Procedure SetInTime(Value : Integer); //Diz o Timeout
Procedure SetEventTimer(Value : TOnEventTimer); //Seta o Evento a ser executado
Public
Constructor Create; //Cria o Componente
Destructor Destroy;Override;//Destroy a Classe
Procedure Assign(Source : TPersistent); Override;
Published
Property AutoCheck : Boolean Read vAutoCheck Write SetState; //Se tem Autochecagem
Property InTime : Integer Read vInTime Write SetInTime; //Em milisegundos o timer
Property OnEventTimer : TOnEventTimer Read vEvent Write SetEventTimer; //Evento a executar
End;
Type
TProxyOptions = Class(TPersistent)
Private
vServer, //Servidor Proxy na Rede
vLogin, //Login do Servidor Proxy
vPassword : String; //Senha do Servidor Proxy
vPort : Integer; //Porta do Servidor Proxy
Public
Constructor Create;
Procedure Assign(Source : TPersistent); Override;
Published
Property Server : String Read vServer Write vServer; //Servidor Proxy na Rede
Property Port : Integer Read vPort Write vPort; //Porta do Servidor Proxy
Property Login : String Read vLogin Write vLogin; //Login do Servidor Proxy
Property Password : String Read vPassword Write vPassword; //Senha do Servidor Proxy
End;
Type
TRESTDataBase = Class(TComponent)
Private
Owner : TComponent; //Proprietario do Componente
vLogin, //Login do Usuário caso haja autenticação
vPassword, //Senha do Usuário caso haja autenticação
vRestWebService, //Rest WebService para consultas
vRestURL, //URL do WebService REST
vRestModule, //Classe Principal do Servidor a ser utilizada
vMyIP, //Meu IP vindo do Servidor
vRestPooler : String; //Qual o Pooler de Conexão do DataSet
vPoolerPort : Integer; //A Porta do Pooler
vProxy : Boolean; //Diz se tem servidor Proxy
vProxyOptions : TProxyOptions; //Se tem Proxy diz quais as opções
vCompression, //Se Vai haver compressão de Dados
vConnected : Boolean; //Diz o Estado da Conexão
vOnEventConnection : TOnEventConnection; //Evento de Estado da Conexão
vOnBeforeConnection : TOnEventBeforeConnection; //Evento antes de Connectar o Database
vAutoCheckData : TAutoCheckData; //Autocheck de Conexão
vTimeOut : Integer;
VEncondig : TEncodeSelect; //Enconding se usar CORS usar UTF8 - Alexandre Abade
vContentex : String ; //Contexto - Alexandre Abade
vRESTContext : String ; //RestContexto - Alexandre Abade
vStrsTrim,
vStrsEmpty2Null,
vStrsTrim2Len : Boolean;
vParamCreate : Boolean;
Procedure SetConnection(Value : Boolean); //Seta o Estado da Conexão
Procedure SetRestPooler(Value : String); //Seta o Restpooler a ser utilizado
Procedure SetPoolerPort(Value : Integer); //Seta a Porta do Pooler a ser usada
Procedure CheckConnection; //Checa o Estado automatico da Conexão
Function TryConnect : Boolean; //Tenta Conectar o Servidor para saber se posso executar comandos
Procedure SetConnectionOptions(Var Value : TDSRestConnection); //Seta as Opções de Conexão
Function ExecuteCommand (Var SQL : TStringList;
Var Params : TParams;
Var Error : Boolean;
Var MessageError : String;
Execute : Boolean = False) : TFDJSONDataSets;
Procedure ExecuteProcedure(ProcName : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String);
Procedure ApplyUpdates(Var SQL : TStringList;
Var Params : TParams;
ADeltaList : TFDJSONDeltas;
TableName : String;
Var Error : Boolean;
Var MessageError : String);
Function InsertMySQLReturnID(Var SQL : TStringList;
Var Params : TParams;
Var Error : Boolean;
Var MessageError : String) : Integer;
Function GetStateDB : Boolean;
Public
Function GetRestPoolers : TStringList; //Retorna a Lista de DataSet Sources do Pooler
Constructor Create(AOwner : TComponent);Override; //Cria o Componente
Destructor Destroy;Override; //Destroy a Classe
Procedure Close;
Procedure Open;
Property Connected : Boolean Read GetStateDB Write SetConnection;
Published
Property OnConnection : TOnEventConnection Read vOnEventConnection Write vOnEventConnection; //Evento relativo a tudo que acontece quando tenta conectar ao Servidor
Property OnBeforeConnect : TOnEventBeforeConnection Read vOnBeforeConnection Write vOnBeforeConnection; //Evento antes de Connectar o Database
Property Active : Boolean Read vConnected Write SetConnection; //Seta o Estado da Conexão
Property Compression : Boolean Read vCompression Write vCompression; //Compressão de Dados
Property MyIP : String Read vMyIP;
Property Login : String Read vLogin Write vLogin; //Login do Usuário caso haja autenticação
Property Password : String Read vPassword Write vPassword; //Senha do Usuário caso haja autenticação
Property Proxy : Boolean Read vProxy Write vProxy; //Diz se tem servidor Proxy
Property ProxyOptions : TProxyOptions Read vProxyOptions Write vProxyOptions; //Se tem Proxy diz quais as opções
Property PoolerService : String Read vRestWebService Write vRestWebService; //Host do WebService REST
Property PoolerURL : String Read vRestURL Write vRestURL; //URL do WebService REST
Property PoolerPort : Integer Read vPoolerPort Write SetPoolerPort; //A Porta do Pooler do DataSet
Property PoolerName : String Read vRestPooler Write SetRestPooler; //Qual o Pooler de Conexão ligado ao componente
Property RestModule : String Read vRestModule Write vRestModule; //Classe do Servidor REST Principal
Property StateConnection : TAutoCheckData Read vAutoCheckData Write vAutoCheckData; //Autocheck da Conexão
Property RequestTimeOut : Integer Read vTimeOut Write vTimeOut; //Timeout da Requisição
Property Encoding : TEncodeSelect Read VEncondig Write VEncondig; //Encoding da string
Property Context : string Read vContentex Write vContentex; //Contexto
Property RESTContext : string Read vRESTContext Write vRESTContext; //Rest Contexto
Property StrsTrim : Boolean Read vStrsTrim Write vStrsTrim;
Property StrsEmpty2Null : Boolean Read vStrsEmpty2Null Write vStrsEmpty2Null;
Property StrsTrim2Len : Boolean Read vStrsTrim2Len Write vStrsTrim2Len;
Property ParamCreate : Boolean read vParamCreate write vParamCreate;
End;
Type
TRESTClientSQL = Class(TFDMemTable) //Classe com as funcionalidades de um DBQuery
Private
vOldStatus : TDatasetState;
vDataSource : TDataSource;
vOnAfterScroll : TOnAfterScroll;
vOnAfterOpen : TOnAfterOpen;
vOnAfterClose : TOnAfterClose;
vOnAfterInsert : TOnAfterInsert;
vOnBeforeDelete : TOnBeforeDelete;
vOnBeforePost : TOnBeforePost;
vOnAfterPost : TOnAfterPost;
Owner : TComponent;
OldData : TMemoryStream;
vActualRec : Integer;
vUpdateTableName : String; //Tabela que será feito Update no Servidor se for usada Reflexão de Dados
vCacheUpdateRecords,
vReadData,
vCascadeDelete,
vBeforeClone,
vDataCache, //Se usa cache local
vConnectedOnce, //Verifica se foi conectado ao Servidor
vCommitUpdates,
vCreateDS,
vErrorBefore,
vActive : Boolean; //Estado do Dataset
vSQL : TStringList; //SQL a ser utilizado na conexão
vParams : TParams; //Parametros de Dataset
vCacheDataDB : TFDDataset; //O Cache de Dados Salvo para utilização rápida
vOnGetDataError : TOnEventConnection; //Se deu erro na hora de receber os dados ou não
vRESTDataBase : TRESTDataBase; //RESTDataBase do Dataset
vOnAfterDelete : TDataSetNotifyEvent;
FieldDefsUPD : TFieldDefs;
vMasterDataSet : TRESTClientSQL;
vMasterDetailList : TMasterDetailList; //DataSet MasterDetail Function
Procedure CloneDefinitions(Source : TFDMemTable;
aSelf : TRESTClientSQL); //Fields em Definições
Procedure OnChangingSQL(Sender: TObject); //Quando Altera o SQL da Lista
Procedure SetActiveDB(Value : Boolean); //Seta o Estado do Dataset
Procedure SetSQL(Value : TStringList); //Seta o SQL a ser usado
Procedure CreateParams; //Cria os Parametros na lista de Dataset
Procedure SetDataBase(Value : TRESTDataBase); //Diz o REST Database
Function GetData : Boolean; //Recebe os Dados da Internet vindo do Servidor REST
Procedure SetUpdateTableName(Value : String); //Diz qual a tabela que será feito Update no Banco
Procedure OldAfterPost(DataSet: TDataSet); //Eventos do Dataset para realizar o AfterPost
Procedure OldAfterDelete(DataSet: TDataSet); //Eventos do Dataset para realizar o AfterDelete
Procedure SetMasterDataSet(Value : TRESTClientSQL);
Procedure PrepareDetails(ActiveMode : Boolean);
Procedure SetCacheUpdateRecords(Value : Boolean);
Procedure PrepareDetailsNew;
Function FirstWord(Value : String) : String;
Property MasterSource;
Procedure ProcAfterScroll (DataSet : TDataSet);
Procedure ProcAfterOpen (DataSet : TDataSet);
Procedure ProcAfterClose (DataSet : TDataSet);
Procedure ProcAfterInsert (DataSet : TDataSet);
Procedure ProcBeforeDelete(DataSet : TDataSet);
Procedure ProcBeforePost (DataSet : TDataSet);
Procedure ProcAfterPost (DataSet : TDataSet);
Protected
Function CanObserve(const ID: Integer): Boolean; Override;
Public
//Métodos
Procedure Open;Overload; Virtual; //Método Open que será utilizado no Componente
Procedure Open(SQL: String);Overload; Virtual; //Método Open que será utilizado no Componente
Procedure ExecOrOpen; //Método Open que será utilizado no Componente
Procedure Close;Virtual; //Método Close que será utilizado no Componente
Procedure CreateDataSet; virtual;
Function ExecSQL(Var Error : String) : Boolean; //Método ExecSQL que será utilizado no Componente
Function InsertMySQLReturnID : Integer; //Método de ExecSQL com retorno de Incremento
Function ParamByName(Value : String) : TParam; //Retorna o Parametro de Acordo com seu nome
Function ApplyUpdates(var Error : String) : Boolean; //Aplica Alterações no Banco de Dados
Constructor Create(AOwner : TComponent);Override; //Cria o Componente
Destructor Destroy;Override; //Destroy a Classe
Procedure Loaded; Override;
procedure OpenCursor(InfoQuery: Boolean); Override; //Subscrevendo o OpenCursor para não ter erros de ADD Fields em Tempo de Design
Procedure GotoRec(Const RecNo : Integer);
Function ParamCount : Integer;
Procedure DynamicFilter(Field, Value : String; InText : Boolean = False);
procedure Refresh;
Published
Property MasterDataSet : TRESTClientSQL Read vMasterDataSet Write SetMasterDataSet;
Property MasterCascadeDelete : Boolean Read vCascadeDelete Write vCascadeDelete;
Property AfterDelete : TDataSetNotifyEvent Read vOnAfterDelete Write vOnAfterDelete;
Property OnGetDataError : TOnEventConnection Read vOnGetDataError Write vOnGetDataError; //Recebe os Erros de ExecSQL ou de GetData
Property AfterScroll : TOnAfterScroll Read vOnAfterScroll Write vOnAfterScroll;
Property AfterOpen : TOnAfterOpen Read vOnAfterOpen Write vOnAfterOpen;
Property AfterClose : TOnAfterClose Read vOnAfterClose Write vOnAfterClose;
Property AfterInsert : TOnAfterInsert Read vOnAfterInsert Write vOnAfterInsert;
Property BeforeDelete : TOnBeforeDelete Read vOnBeforeDelete Write vOnBeforeDelete;
Property BeforePost : TOnBeforePost Read vOnBeforePost Write vOnBeforePost;
Property AfterPost : TOnAfterPost Read vOnAfterPost Write vOnAfterPost;
Property Active : Boolean Read vActive Write SetActiveDB; //Estado do Dataset
Property DataCache : Boolean Read vDataCache Write vDataCache; //Diz se será salvo o último Stream do Dataset
Property Params : TParams Read vParams Write vParams; //Parametros de Dataset
Property DataBase : TRESTDataBase Read vRESTDataBase Write SetDataBase; //Database REST do Dataset
Property SQL : TStringList Read vSQL Write SetSQL; //SQL a ser Executado
Property UpdateTableName : String Read vUpdateTableName Write SetUpdateTableName; //Tabela que será usada para Reflexão de Dados
Property CacheUpdateRecords : Boolean Read vCacheUpdateRecords Write SetCacheUpdateRecords;
End;
Type
TRESTStoredProc = Class(TComponent)
Private
Owner : TComponent;
vParams : TParams;
vProcName : String;
vRESTDataBase : TRESTDataBase;
procedure SetDataBase(Const Value : TRESTDataBase);
Public
Constructor Create (AOwner : TComponent);Override; //Cria o Componente
Function ExecProc (Var Error : String) : Boolean;
Destructor Destroy;Override; //Destroy a Classe
Function ParamByName(Value : String) : TParam;
Published
Property DataBase : TRESTDataBase Read vRESTDataBase Write SetDataBase; //Database REST do Dataset
Property Params : TParams Read vParams Write vParams; //Parametros de Dataset
Property ProcName : String Read vProcName Write vProcName; //Procedure a ser Executada
End;
Type
TRESTPoolerList = Class(TComponent)
Private
Owner : TComponent; //Proprietario do Componente
vPoolerPrefix, //Prefixo do WS
vLogin, //Login do Usuário caso haja autenticação
vPassword, //Senha do Usuário caso haja autenticação
vRestWebService, //Rest WebService para consultas
vRestURL : String; //Qual o Pooler de Conexão do DataSet
vPoolerPort : Integer; //A Porta do Pooler
vConnected,
vProxy : Boolean; //Diz se tem servidor Proxy
vProxyOptions : TProxyOptions; //Se tem Proxy diz quais as opções
vPoolerList : TStringList;
Procedure SetConnection(Value : Boolean); //Seta o Estado da Conexão
Procedure SetPoolerPort(Value : Integer); //Seta a Porta do Pooler a ser usada
Function TryConnect : Boolean; //Tenta Conectar o Servidor para saber se posso executar comandos
Procedure SetConnectionOptions(Var Value : TDSRestConnection); //Seta as Opções de Conexão
Public
Constructor Create(AOwner : TComponent);Override; //Cria o Componente
Destructor Destroy;Override; //Destroy a Classe
Published
Property Active : Boolean Read vConnected Write SetConnection; //Seta o Estado da Conexão
Property Login : String Read vLogin Write vLogin; //Login do Usuário caso haja autenticação
Property Password : String Read vPassword Write vPassword; //Senha do Usuário caso haja autenticação
Property Proxy : Boolean Read vProxy Write vProxy; //Diz se tem servidor Proxy
Property ProxyOptions : TProxyOptions Read vProxyOptions Write vProxyOptions; //Se tem Proxy diz quais as opções
Property PoolerService : String Read vRestWebService Write vRestWebService; //Host do WebService REST
Property PoolerURL : String Read vRestURL Write vRestURL; //URL do WebService REST
Property PoolerPort : Integer Read vPoolerPort Write SetPoolerPort; //A Porta do Pooler do DataSet
Property PoolerPrefix : String Read vPoolerPrefix Write vPoolerPrefix; //Prefixo do WebService REST
Property Poolers : TStringList Read vPoolerList;
End;
{$IFDEF MSWINDOWS}
Type
TRESTDriver = Class(TComponent)
Private
vStrsTrim,
vStrsEmpty2Null,
vStrsTrim2Len,
vCompression : Boolean;
vEncoding : TEncodeSelect;
vParamCreate : Boolean;
Public
Procedure ApplyChanges (TableName,
SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String;
Const ADeltaList : TFDJSONDeltas);Overload;Virtual; abstract;
Procedure ApplyChanges (TableName,
SQL : String;
Var Error : Boolean;
Var MessageError : String;
Const ADeltaList : TFDJSONDeltas);Overload;Virtual; abstract;
Function ExecuteCommand (SQL : String;
Var Error : Boolean;
Var MessageError : String;
Execute : Boolean = False) : TFDJSONDataSets;Overload;Virtual;abstract;
Function ExecuteCommand (SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String;
Execute : Boolean = False) : TFDJSONDataSets;Overload;Virtual;abstract;
Function InsertMySQLReturnID (SQL : String;
Var Error : Boolean;
Var MessageError : String) : Integer;Overload;Virtual;abstract;
Function InsertMySQLReturnID (SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String) : Integer;Overload;Virtual;abstract;
Procedure ExecuteProcedure (ProcName : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String);Virtual;abstract;
Procedure ExecuteProcedurePure(ProcName : String;
Var Error : Boolean;
Var MessageError : String);Virtual;abstract;
Procedure Close;Virtual;abstract;
Public
Property StrsTrim : Boolean Read vStrsTrim Write vStrsTrim;
Property StrsEmpty2Null : Boolean Read vStrsEmpty2Null Write vStrsEmpty2Null;
Property StrsTrim2Len : Boolean Read vStrsTrim2Len Write vStrsTrim2Len;
Property Compression : Boolean Read vCompression Write vCompression;
Property Encoding : TEncodeSelect Read vEncoding Write vEncoding;
property ParamCreate : Boolean read vParamCreate write vParamCreate;
End;
//PoolerDB Control
Type
TRESTPoolerDBP = ^TComponent;
TRESTPoolerDB = Class(TComponent)
Private
Owner : TComponent;
FLock : TCriticalSection;
vRESTDriverBack,
vRESTDriver : TRESTDriver;
vActive,
vStrsTrim,
vStrsEmpty2Null,
vStrsTrim2Len,
vCompression : Boolean;
vEncoding : TEncodeSelect;
vMessagePoolerOff : String;
vParamCreate : Boolean;
Procedure SetConnection(Value : TRESTDriver);
Function GetConnection : TRESTDriver;
Public
Procedure ApplyChanges(TableName,
SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String;
Const ADeltaList : TFDJSONDeltas);Overload;
Procedure ApplyChanges(TableName,
SQL : String;
Var Error : Boolean;
Var MessageError : String;
Const ADeltaList : TFDJSONDeltas);Overload;
Function ExecuteCommand(SQL : String;
Var Error : Boolean;
Var MessageError : String;
Execute : Boolean = False) : TFDJSONDataSets;Overload;
Function ExecuteCommand(SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String;
Execute : Boolean = False) : TFDJSONDataSets;Overload;
Function InsertMySQLReturnID(SQL : String;
Var Error : Boolean;
Var MessageError : String) : Integer;Overload;
Function InsertMySQLReturnID(SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String) : Integer;Overload;
Procedure ExecuteProcedure (ProcName : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String);
Procedure ExecuteProcedurePure(ProcName : String;
Var Error : Boolean;
Var MessageError : String);
Constructor Create(AOwner : TComponent);Override; //Cria o Componente
Destructor Destroy;Override; //Destroy a Classe
Published
Property RESTDriver : TRESTDriver Read GetConnection Write SetConnection;
Property Compression : Boolean Read vCompression Write vCompression;
Property Encoding : TEncodeSelect Read vEncoding Write vEncoding;
Property StrsTrim : Boolean Read vStrsTrim Write vStrsTrim;
Property StrsEmpty2Null : Boolean Read vStrsEmpty2Null Write vStrsEmpty2Null;
Property StrsTrim2Len : Boolean Read vStrsTrim2Len Write vStrsTrim2Len;
Property Active : Boolean Read vActive Write vActive;
Property PoolerOffMessage : String Read vMessagePoolerOff Write vMessagePoolerOff;
Property ParamCreate : Boolean Read vParamCreate Write vParamCreate;
End;
{$ENDIF}
Function DecodeStrings(Value : String;Encoding:TEncoding) : String;
Function GetEncoding(Avalue : TEncodeSelect) : TEncoding;
Function EncodeStrings(Value : String) : String;
Procedure doUnGZIP(Input, gZipped : TMemoryStream);//helper function
Procedure doGZIP (Input, gZipped : TMemoryStream);//helper function
implementation
Procedure doGZIP(Input, gZipped : TMemoryStream);//helper function
Const
GZIP = 31;//very important because gzip is a linux zip format
Var
CompactadorGZip : TZCompressionStream;
Begin
Input.Position := 0;
CompactadorGZip := TZCompressionStream.Create(gZipped, zcMax, GZIP);
CompactadorGZip.CopyFrom(Input, Input.Size);
CompactadorGZip.Free;
gZipped.Position := 0;
End;
Procedure doUnGZIP(Input, gZipped : TMemoryStream);//helper function
Const
GZIP = 31;//very important because gzip is a linux zip format
Var
CompactadorGZip : TZDecompressionStream;
Begin
Input.Position := 0;
CompactadorGZip := TZDecompressionStream.Create(Input, GZIP);
gZipped.CopyFrom(CompactadorGZip, CompactadorGZip.Size);
CompactadorGZip.Free;
gZipped.Position := 0;
End;
Function GetEncoding(Avalue : TEncodeSelect) : TEncoding;
Begin
Result := TEncoding.utf8; // definido como padrão para suprimir Warn no delphi
Case Avalue of
esUtf8 : Result := TEncoding.utf8;
esASCII : Result := TEncoding.ASCII;
End;
End;
Function EncodeStrings(Value : String) : String;
Var
Input,
Output : TStringStream;
Begin
Input := TStringStream.Create(Value, TEncoding.ASCII);
Try
Input.Position := 0;
Output := TStringStream.Create('', TEncoding.ASCII);
Try
Soap.EncdDecd.EncodeStream(Input, Output);
Result := Output.DataString;
Finally
Output.Free;
End;
Finally
Input.Free;
End;
End;
Function DecodeStrings(Value : String;Encoding:TEncoding) : String;
Var
Input,
Output : TStringStream;
Begin
If Length(Value) > 0 Then
Begin
Input := TStringStream.Create(Value, Encoding);
Try
Output := TStringStream.Create('', Encoding);
Try
Soap.EncdDecd.DecodeStream(Input, Output);
Output.Position := 0;
Try
Result := Output.DataString;
Except
Raise;
End;
Finally
Output.Free;
End;
Finally
Input.Free;
End;
End;
End;
Procedure TAutoCheckData.Assign(Source: TPersistent);
Var
Src : TAutoCheckData;
Begin
If Source is TAutoCheckData Then
Begin
Src := TAutoCheckData(Source);
vAutoCheck := Src.AutoCheck;
vInTime := Src.InTime;
// vEvent := Src.OnEventTimer;
End
Else
Inherited;
End;
Procedure TProxyOptions.Assign(Source: TPersistent);
Var
Src : TProxyOptions;
Begin
If Source is TProxyOptions Then
Begin
Src := TProxyOptions(Source);
vServer := Src.Server;
vLogin := Src.Login;
vPassword := Src.Password;
vPort := Src.Port;
End
Else
Inherited;
End;
{$IFDEF MSWINDOWS}
Function TRESTPoolerDB.GetConnection : TRESTDriver;
Begin
Result := vRESTDriverBack;
End;
Procedure TRESTPoolerDB.SetConnection(Value : TRESTDriver);
Begin
vRESTDriverBack := Value;
If Value <> Nil Then
vRESTDriver := vRESTDriverBack
Else
Begin
If vRESTDriver <> Nil Then
vRESTDriver.Close;
End;
End;
Function TRESTPoolerDB.InsertMySQLReturnID(SQL : String;
Var Error : Boolean;
Var MessageError : String) : Integer;
Begin
Result := -1;
If vRESTDriver <> Nil Then
Begin
vRESTDriver.vStrsTrim := vStrsTrim;
vRESTDriver.vStrsEmpty2Null := vStrsEmpty2Null;
vRESTDriver.vStrsTrim2Len := vStrsTrim2Len;
vRESTDriver.vCompression := vCompression;
vRESTDriver.vEncoding := vEncoding;
vRESTDriver.vParamCreate := vParamCreate;
Result := vRESTDriver.InsertMySQLReturnID(SQL, Error, MessageError);
End
Else
Begin
Error := True;
MessageError := 'Selected Pooler Does Not Have a Driver Set';
End;
End;
Function TRESTPoolerDB.InsertMySQLReturnID(SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String) : Integer;
Begin
Result := -1;
If vRESTDriver <> Nil Then
Begin
vRESTDriver.vStrsTrim := vStrsTrim;
vRESTDriver.vStrsEmpty2Null := vStrsEmpty2Null;
vRESTDriver.vStrsTrim2Len := vStrsTrim2Len;
vRESTDriver.vCompression := vCompression;
vRESTDriver.vEncoding := vEncoding;
vRESTDriver.vParamCreate := vParamCreate;
Result := vRESTDriver.InsertMySQLReturnID(SQL, Params, Error, MessageError);
End
Else
Begin
Error := True;
MessageError := 'Selected Pooler Does Not Have a Driver Set';
End;
End;
Function TRESTPoolerDB.ExecuteCommand(SQL : String;
Var Error : Boolean;
Var MessageError : String;
Execute : Boolean = False) : TFDJSONDataSets;
Begin
Result := nil;
If vRESTDriver <> Nil Then
Begin
vRESTDriver.vStrsTrim := vStrsTrim;
vRESTDriver.vStrsEmpty2Null := vStrsEmpty2Null;
vRESTDriver.vStrsTrim2Len := vStrsTrim2Len;
vRESTDriver.vCompression := vCompression;
vRESTDriver.vEncoding := vEncoding;
vRESTDriver.vParamCreate := vParamCreate;
Result := vRESTDriver.ExecuteCommand(SQL, Error, MessageError, Execute);
End
Else
Begin
Error := True;
MessageError := 'Selected Pooler Does Not Have a Driver Set';
End;
End;
Function TRESTPoolerDB.ExecuteCommand(SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String;
Execute : Boolean = False) : TFDJSONDataSets;
Begin
Result := Nil;
If vRESTDriver <> Nil Then
Begin
vRESTDriver.vStrsTrim := vStrsTrim;
vRESTDriver.vStrsEmpty2Null := vStrsEmpty2Null;
vRESTDriver.vStrsTrim2Len := vStrsTrim2Len;
vRESTDriver.vCompression := vCompression;
vRESTDriver.vEncoding := vEncoding;
vRESTDriver.vParamCreate := vParamCreate;
Result := vRESTDriver.ExecuteCommand(SQL, Params, Error, MessageError, Execute);
End
Else
Begin
Error := True;
MessageError := 'Selected Pooler Does Not Have a Driver Set';
End;
End;
Procedure TRESTPoolerDB.ExecuteProcedure(ProcName : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String);
Begin
If vRESTDriver <> Nil Then
Begin
vRESTDriver.vStrsTrim := vStrsTrim;
vRESTDriver.vStrsEmpty2Null := vStrsEmpty2Null;
vRESTDriver.vStrsTrim2Len := vStrsTrim2Len;
vRESTDriver.vCompression := vCompression;
vRESTDriver.vEncoding := vEncoding;
vRESTDriver.vParamCreate := vParamCreate;
vRESTDriver.ExecuteProcedure(ProcName, Params, Error, MessageError);
End
Else
Begin
Error := True;
MessageError := 'Selected Pooler Does Not Have a Driver Set';
End;
End;
Procedure TRESTPoolerDB.ExecuteProcedurePure(ProcName : String;
Var Error : Boolean;
Var MessageError : String);
Begin
If vRESTDriver <> Nil Then
Begin
vRESTDriver.vStrsTrim := vStrsTrim;
vRESTDriver.vStrsEmpty2Null := vStrsEmpty2Null;
vRESTDriver.vStrsTrim2Len := vStrsTrim2Len;
vRESTDriver.vCompression := vCompression;
vRESTDriver.vEncoding := vEncoding;
vRESTDriver.vParamCreate := vParamCreate;
vRESTDriver.ExecuteProcedurePure(ProcName, Error, MessageError);
End
Else
Begin
Error := True;
MessageError := 'Selected Pooler Does Not Have a Driver Set';
End;
End;
Procedure TRESTPoolerDB.ApplyChanges(TableName,
SQL : String;
Var Error : Boolean;
Var MessageError : String;
Const ADeltaList : TFDJSONDeltas);
begin
If vRESTDriver <> Nil Then
Begin
vRESTDriver.vStrsTrim := vStrsTrim;
vRESTDriver.vStrsEmpty2Null := vStrsEmpty2Null;
vRESTDriver.vStrsTrim2Len := vStrsTrim2Len;
vRESTDriver.vCompression := vCompression;
vRESTDriver.vEncoding := vEncoding;
vRESTDriver.vParamCreate := vParamCreate;
vRESTDriver.ApplyChanges(TableName, SQL, Error, MessageError, ADeltaList);
End
Else
Begin
Error := True;
MessageError := 'Selected Pooler Does Not Have a Driver Set';
End;
end;
Procedure TRESTPoolerDB.ApplyChanges(TableName,
SQL : String;
Params : TParams;
Var Error : Boolean;
Var MessageError : String;
Const ADeltaList : TFDJSONDeltas);
begin
If vRESTDriver <> Nil Then
Begin
vRESTDriver.vStrsTrim := vStrsTrim;
vRESTDriver.vStrsEmpty2Null := vStrsEmpty2Null;
vRESTDriver.vStrsTrim2Len := vStrsTrim2Len;
vRESTDriver.vCompression := vCompression;
vRESTDriver.vEncoding := vEncoding;
vRESTDriver.vParamCreate := vParamCreate;
vRESTDriver.ApplyChanges(TableName, SQL, Params, Error, MessageError, ADeltaList);
End
Else
Begin
Error := True;
MessageError := 'Selected Pooler Does Not Have a Driver Set';
End;
end;
Constructor TRESTPoolerDB.Create(AOwner : TComponent);
Begin
Inherited;
Owner := aOwner;
FLock := TCriticalSection.Create;
vCompression := True;
vStrsTrim := False;
vStrsEmpty2Null := False;
vStrsTrim2Len := True;
vActive := True;
vEncoding := esUtf8;
vMessagePoolerOff := 'RESTPooler not active.';
vParamCreate := True;
End;
Destructor TRESTPoolerDB.Destroy;
Begin
FLock.Release;
FLock.DisposeOf;
Inherited;
End;
{$ENDIF}
Constructor TAutoCheckData.Create;
Begin
Inherited;
vAutoCheck := False;
vInTime := 1000;
vEvent := Nil;
Timer := Nil;
FLock := TCriticalSection.Create;
End;
Destructor TAutoCheckData.Destroy;
Begin
SetState(False);
FLock.Release;
FLock.DisposeOf;
Inherited;
End;
Procedure TAutoCheckData.SetState(Value : Boolean);
Begin
vAutoCheck := Value;
If vAutoCheck Then
Begin
If Timer <> Nil Then
Begin
Timer.Terminate;
Timer := Nil;
End;
Timer := TTimerData.Create(vInTime, FLock);
Timer.OnEventTimer := vEvent;
End
Else
Begin
If Timer <> Nil Then
Begin
Timer.Terminate;
Timer := Nil;
End;
End;
End;
Procedure TAutoCheckData.SetInTime(Value : Integer);
Begin
vInTime := Value;
SetState(vAutoCheck);
End;
Procedure TAutoCheckData.SetEventTimer(Value : TOnEventTimer);
Begin
vEvent := Value;
SetState(vAutoCheck);
End;
Constructor TTimerData.Create(AValue: Integer; ALock: TCriticalSection);
Begin
FValue := AValue;
FLock := ALock;
Inherited Create(False);
End;
Procedure TTimerData.Execute;
Begin
While Not Terminated do
Begin
Sleep(FValue);
FLock.Acquire;
if Assigned(vEvent) then
vEvent;
FLock.Release;
End;
End;
Constructor TProxyOptions.Create;
Begin
Inherited;
vServer := '';
vLogin := vServer;
vPassword := vLogin;
vPort := 8888;
End;
Procedure TRESTPoolerList.SetConnectionOptions(Var Value : TDSRestConnection);
Begin
Value := TDSRestConnection.Create(Nil);
Value.LoginPrompt := False;
Value.PreserveSessionID := False;
Value.Protocol := 'http';
Value.Host := vRestWebService;
Value.Port := vPoolerPort;
Value.UrlPath := vRestURL;
Value.UserName := vLogin;
Value.Password := vPassword;
if vProxy then
Begin
Value.ProxyHost := vProxyOptions.vServer;
Value.ProxyPort := vProxyOptions.vPort;
Value.ProxyUsername := vProxyOptions.vLogin;
Value.ProxyPassword := vProxyOptions.vPassword;
End
Else
Begin
Value.ProxyHost := '';
Value.ProxyPort := 0;
Value.ProxyUsername := '';
Value.ProxyPassword := '';
End;
End;
Procedure TRESTDataBase.SetConnectionOptions(Var Value : TDSRestConnection);
Begin
Value := TDSRestConnection.Create(Nil);
Value.LoginPrompt := False;
Value.PreserveSessionID := False;
Value.Protocol := 'http';
Value.Host := vRestWebService;
Value.Port := vPoolerPort;
Value.UrlPath := vRestURL;
Value.UserName := vLogin;
Value.Password := vPassword;
{$if CompilerVersion >= 28}
Value.HTTP.ConnectTimeout := vTimeOut;
{$endif}
Value.RESTContext := vRESTContext;
Value.Context := vContentex;
If vProxy Then
Begin
Value.ProxyHost := vProxyOptions.vServer;
Value.ProxyPort := vProxyOptions.vPort;
Value.ProxyUsername := vProxyOptions.vLogin;
Value.ProxyPassword := vProxyOptions.vPassword;
End
Else
Begin
Value.ProxyHost := '';
Value.ProxyPort := 0;
Value.ProxyUsername := '';
Value.ProxyPassword := '';
End;
End;
Procedure TRESTDataBase.ApplyUpdates(Var SQL : TStringList;
Var Params : TParams;
ADeltaList : TFDJSONDeltas;
TableName : String;
Var Error : Boolean;
Var MessageError : String);
Var
vDSRConnection : TDSRestConnection;
vRESTConnectionDB : TSMPoolerMethodClient;
Function GetLineSQL(Value : TStringList) : String;
Var
I : Integer;
Begin
Result := '';
If Value <> Nil Then
For I := 0 To Value.Count -1 do
Begin
If I = 0 then
Result := Value[I]
Else
Result := Result + ' ' + Value[I];
End;
End;
Begin
if vRestPooler = '' then
Exit;
SetConnectionOptions(vDSRConnection);
vRESTConnectionDB := TSMPoolerMethodClient.Create(vDSRConnection, True);
vRESTConnectionDB.Compression := vCompression;
vRESTConnectionDB.Encoding := GetEncoding(VEncondig);
Try
If Params.Count > 0 Then
vRESTConnectionDB.ApplyChanges(vRestPooler,
vRestModule,
TableName,
GetLineSQL(SQL),
Params,
ADeltaList,
Error,
MessageError, '',
vTimeOut, vLogin, vPassword)
Else
vRESTConnectionDB.ApplyChangesPure(vRestPooler,
vRestModule,
TableName,
GetLineSQL(SQL),
ADeltaList,
Error,
MessageError, '',
vTimeOut, vLogin, vPassword);
If Assigned(vOnEventConnection) Then
vOnEventConnection(True, 'ApplyUpdates Ok')
Except