-
Notifications
You must be signed in to change notification settings - Fork 2
/
fbcustomdataset.pas
5711 lines (5213 loc) · 164 KB
/
fbcustomdataset.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
(********************************************************************************)
(* FB/IB Data set (FBDataSet) *)
(* *)
(* The contents of this file are subject to the GNU LIBRARY GENERAL PUBLIC *)
(* LICENSE 2 (the "License"); you may not use this file except in compliance *)
(* with the License. You may obtain a copy of the License at *)
(* http://www.gnu.org/copyleft/lesser.html *)
(* *)
(* Software distributed under the License is distributed on an "AS IS" basis, *)
(* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for *)
(* the specific language governing rights and limitations under the License. *)
(* *)
(* Unit owner : Lagunov Aleksey <alexs75@hotbox.ru> *)
(* *)
(********************************************************************************)
{$I fb_define.inc}
//UTF8-RU-ansi used
unit fbcustomdataset;
interface
uses
SysUtils, Classes, DB, mydbunit, uiblib, uib, fbmisc, fbparams,
uibase,
{$IFDEF FB_USE_LCL}
ExtCtrls, Forms, Controls,
{$ENDIF}
IniFiles {use THashedStringList}
;
type
TFieldHeader = class
FieldName:string;
FieldNo:integer;
FieldType:TFieldType;
FieldSize:Cardinal;
FieldPrecision:integer;
FieldOffs:Cardinal;
FieldRequired:boolean;
{used to denote that field data uses as AnsiString/WideString types for
ftString Field type}
{(UTF8-RU-ansi) указывает что используется динамический тип данных - в рекорде
реально храница указатель на данные.}
FieldIsDinamicData : boolean;
FieldOrigin:string;
{this tag used for fields selection that need to save/load thair cache cells,
at present BLOB are maintained}
IsCached : boolean;
end;
PFieldHeader = TFieldHeader;
FieldHeaderIndex = integer;
{ TFieldsHeader }
TFieldsHeader = class(TList)
private
function GetFieldHeader(Index: Integer): TFieldHeader;
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
property FieldHeader[Index: Integer]:TFieldHeader read GetFieldHeader; default;
function HeaderByName(AName:string):TFieldHeader;
end;
const
{(UTF8-RU-ansi) граница минимальной длинны строки, начиная с которой выгодно ее
хранить в ansiString}
AnsiMinSizeTh = 31;
{this constants used by FBAnsiField class to access Get/SetData methods}
fdNativeData = true;
fdConvertData = false;
type
IntegersArray = array of integer;
{grow Dest array for 1 value and set one to a last array cell, returns an length of Dest}
function AppendItem( var Dest : IntegersArray; Value : integer) : integer;
type
TBlobCacheStream = class;
TRecordsBufferIndex = class;
{(UTF8-RU-ansi) ета запись используется для выборки БЛОБА из буфера записи методами Get/SetFieldData}
{this type use for retrieve BLOB with Get/SetField methods}
PBLOBFieldData = ^TBLOBFieldData;
TBLOBFieldData = record
IscQuad : TIscQuad;
Cache : TBlobCacheStream;
end;
TRecordsBuffer = class;
TFBCustomDataSet = class;
TFBUpdateRecordTypes = set of TCachedUpdateStatus;
TFBDataLink = class(TDetailDataLink)
protected
FFBCustomDataSet: TFBCustomDataSet;
protected
procedure ActiveChanged; override;
procedure RecordChanged(Field: TField); override;
function GetDetailDataSet: TDataSet; override;
public
constructor Create(AFBCustomDataSet: TFBCustomDataSet);
destructor Destroy; override;
end;
TAutoUpdateOptions = class(TPersistent)
private
FOwner:TFBCustomDataSet;
FUpdateTableName: string; //Updated table
FKeyField: string;
FWhenGetGenID: TWhenGetGenID;
FIncrementBy: integer;
FGeneratorName: string; //Key field
procedure SetKeyField(const AValue: string);
procedure SetUpdateTableName(const AValue: string);
procedure SetWhenGetGenID(const AValue: TWhenGetGenID);
procedure SetGeneratorName(const AValue: string);
procedure SetIncrementBy(const AValue: integer);
public
constructor Create(AOwner:TFBCustomDataSet);
destructor Destroy; override;
procedure ApplyGetGenID;
procedure Assign(Source: TPersistent); override;
function IsComplete:boolean;
published
property KeyField:string read FKeyField write SetKeyField;
property UpdateTableName:string read FUpdateTableName write SetUpdateTableName;
property WhenGetGenID:TWhenGetGenID read FWhenGetGenID write SetWhenGetGenID;
property GeneratorName:string read FGeneratorName write SetGeneratorName;
property IncrementBy:integer read FIncrementBy write SetIncrementBy;
end;
(*
TFBTimeField = class(TTimeField)
protected
procedure SetAsString(const AValue: string); override;
end;
*)
TFBAnsiMemoField = class(TMemoField)
protected
function GetAsString: string; override;
procedure SetAsString(const Value: string); override;
function GetIsNull: Boolean; override;
end;
FBAnsiMemoField = TFBAnsiMemoField;
TFBAnsiField = class(TStringField)
protected
{uses for fast field access}
NativeDataSet : TFBCustomDataSet;
procedure SetDataSet(ADataSet: TDataSet); override;
procedure SetData(const Data: AnsiString);overload;
procedure CopyData(Source, Dest: Pointer); {$IFNDEF FPC}override;{$ENDIF}
function GetAsString: string; override;
function GetAsVariant: Variant; override;
function GetAsAnsiString: AnsiString;
function GetDataSize: Integer; override;
procedure SetAsAnsiString(const Value: AnsiString); virtual;
procedure SetAsString(const Value: AnsiString); overload;
{$IFOPT H+}override;{$ELSE}virtual;{$ENDIF}
// procedure SetAsString(const Value: ShortString); overload;
// {$IFOPT H+}virtual;{$ELSE}override;{$ENDIF}
procedure SetVarValue(const Value: Variant); override;
public
property AsString: AnsiString read GetAsAnsiString write SetAsAnsiString;
property Value: AnsiString read GetAsAnsiString write SetAsAnsiString;
end;
FBAnsiField = TFBAnsiField;
{$IFDEF FPC}
TFBBlobField = class(TBlobField)
protected
procedure AssignTo(Dest: TPersistent); override;
public
procedure SaveToStrings(Strings: TStrings);
end;
{$ENDIF}
{ TFBLargeintField }
TFBLargeintField = class(TLargeintField)
protected
procedure GetText(var AText: string; ADisplayText: Boolean); override;
end;
TDSBLOBCacheList = TList;
{ TFBCustomDataSet }
TFBCustomDataSet = class(TMyDBCustomDataSet)
private
procedure SetRefreshTransactionKind(AValue: TTransactionKind);
protected
FDataBase:TUIBDataBase;
FMasterScrollBehavior: TMasterScrollBehavior;
FOnFetchRecord: TNotifyEvent;
FQuerySelect:TUIBQuery;
FQueryRefresh:TUIBQuery;
FQueryInsert:TUIBQuery;
FQueryEdit:TUIBQuery;
FQueryDelete:TUIBQuery;
FFiledsHeader:TFieldsHeader;
FRecordsBuffer:TRecordsBuffer;
FRecordCount:integer;
FOption: TFBDsOptions;
FCachedUpdates: Boolean;
FAllowedUpdateKinds: TUpdateKinds;
FAutoUpdateOptions: TAutoUpdateOptions;
FRefreshTransactionKind: TTransactionKind;
{$IFDEF FB_USE_LCL}
FSQLScreenCursor: TCursor;
FDetailWaitTimer:TTimer;
{$ENDIF}
FUpdateRecordTypes: TFBUpdateRecordTypes;
//Master-detail support
FMasterFBDataLink:TFBDataLink;
FDetailConditions: TDetailConditions;
//Macro support - based on RXQuery from rxlib
FSaveQueryChanged: TNotifyEvent;
FMacros: TFBParams;
FMacroChar: Char;
FPatternChanged: Boolean;
FSQLPattern: TStrings;
FStreamPatternChanged: Boolean;
FDisconnectExpected: Boolean;
FAutoCommit: boolean;
FDefaultFormats: TDefaultFormats;
FBFCurrentOperationState:TBFCurrentOperationState;
procedure DoFillParams(Qu:TUIBQuery; OnlyMaster:boolean);
//Macro support - based on RXQuery from rxlib
procedure RecreateMacros;
procedure CreateMacros(List: TFBParams; const Value: PChar);
procedure PatternChanged(Sender: TObject);
procedure Expand(Query: TStrings);
procedure QueryChanged(Sender: TObject);
//Master-detail
procedure MasterUpdate(MasterUpdateStatus:TMasterUpdateStatus);
//Property metods
procedure SetTransaction(const AValue: TUIBTransaction);
procedure SetDataBase(const AValue: TUIBDataBase);
function GetSQLRefresh: TStrings;
function GetSQLSelect: TStrings;
procedure SetSQLRefresh(const AValue: TStrings);
procedure SetSQLSelect(const AValue: TStrings);
function GetParams: TSQLParams;
function GetSQLDelete: TStrings;
function GetSQLEdit: TStrings;
procedure SetSQLDelete(const AValue: TStrings);
procedure SetSQLEdit(const AValue: TStrings);
procedure SetOption(const AValue: TFBDsOptions);
procedure SetCachedUpdates(const AValue: Boolean);
procedure SetAllowedUpdateKinds(const AValue: TUpdateKinds);
procedure SetDetailConditions(const AValue: TDetailConditions);
procedure SetAutoUpdateOptions(const AValue: TAutoUpdateOptions);
function GetSQLInsert: TStrings;
procedure SetSQLInsert(const AValue: TStrings);
function GetMacros: TFBParams;
procedure SetMacroChar(const AValue: Char);
procedure SetMacros(const AValue: TFBParams);
function GetMacroCount: Word;
procedure SetUpdateRecordTypes(const AValue: TFBUpdateRecordTypes);
function StoreUpdateTransaction:boolean;
function GetTransaction: TUIBTransaction;
function GetUpdateTransaction: TUIBTransaction;
procedure SetUpdateTransaction(const AValue: TUIBTransaction);
function CheckUpdateKind(UpdateKind:TUpdateKind):boolean;
procedure SetAutoCommit(const AValue: boolean);
procedure UpdateStart;
procedure UpdateCommit;
function IsVisible(Buffer: PChar): Boolean;
procedure SetDefaultFormats(const AValue: TDefaultFormats);
procedure UpdateFieldsFormat;
procedure QuerySelectOnClose(Sender: TObject);
procedure FillEmptyEPFromSelectPar(const Q: TUIBQuery; const ParName:string);
function DoPrepareUIBQuery(const Q: TUIBQuery): boolean;
protected
// FMaxMEMOStringSize : cardinal;
{use by BLOB caches to show that record data affected by caches}
{$IFDEF USE_SAFE_CODE}
FBLOBCache : TDSBLOBCacheList;
{$ENDIF}
FCachedFieldsCount : cardinal;
FCachedFields : IntegersArray;
FInspectRecNo:integer;
FInspectRecord : PRecordBuffer;
function IsInspecting : boolean; {$IFDEF FPC} inline; {$ENDIF}
function GetActiveBuf: PChar;reintroduce;
protected
CalcFieldsMap : array of FieldHeaderIndex;
function GetCalcFieldNo(Offset : cardinal) : FieldHeaderIndex; {$IFDEF FPC} inline; {$ENDIF}
function HeaderId(const Field : TField) : FieldHeaderIndex; {$IFDEF FPC} inline; {$ENDIF}
protected
// overrided metods
procedure DoBeforeDelete; override;
procedure DoBeforeEdit; override;
procedure DoBeforeInsert; override;
procedure BindFields(Binding: Boolean); override;
procedure InternalInitFieldDefs; override;
procedure InternalClose; override;
procedure InternalOpen; override;
function GetRecord(Buffer: PChar; GetMode: TGetMode;
DoCheck: Boolean): TGetResult; override;
procedure SetFieldData(Field: TField; Buffer: Pointer); overload; override;
procedure SetFieldData(Field: TField; const Data : AnsiString);overload;virtual;
procedure SetFieldData2Record(Field: TField; Buffer: Pointer;const RecBuf : PRecordBuffer);overload;virtual;
procedure SetFieldData2Record(Field: TField; const Data : AnsiString; const RecBuf : PRecordBuffer);overload;virtual;
procedure SetBLOBCache(Field: TField; Buffer: PBLOBFieldData); virtual;
function InternalRecordCount: Integer; override;
procedure InternalAfterOpen; override;
procedure InternalEdit; override;
procedure InternalLast; override;
procedure InternalRefresh; override;
procedure InternalRefreshRow(UIBQuery:TUIBQuery);
procedure InternalPost; override;
procedure InternalDelete; override;
procedure InternalAddRecord(Buffer: Pointer; Append: Boolean);override;
procedure SetFiltered(Value: Boolean); override;
function GetDataSource: TDataSource; override;
procedure DoOnNewRecord; override;
procedure Loaded; override;
function GetFieldClass(FieldType: TFieldType): TFieldClass; override;
function IsEmptyEx: Boolean;override;
// internal metods
function BookmarkValid(ABookmark: TBookmark): Boolean; override;
procedure InternalGotoBookmark(ABookmark: Pointer); override;
procedure InternalSaveRecord(const Q:TUIBQuery; FBuff: PChar);
procedure SetDataSource(AValue: TDataSource);
procedure SetFieldsFromParams;
procedure ForceMasterRefresh;
function GetAnyRecField(SrcRecNo:integer; AField:TField):variant;
//
property AllowedUpdateKinds:TUpdateKinds read FAllowedUpdateKinds write SetAllowedUpdateKinds default [ukModify, ukInsert, ukDelete];
property AutoCommit:boolean read FAutoCommit write SetAutoCommit default False;
property DataBase:TUIBDataBase read FDataBase write SetDataBase;
property DataSource: TDataSource read GetDataSource write SetDataSource;
property DefaultFormats:TDefaultFormats read FDefaultFormats write SetDefaultFormats;
property DetailConditions:TDetailConditions read FDetailConditions write SetDetailConditions;
property CachedUpdates: Boolean read FCachedUpdates write SetCachedUpdates default False;
property Transaction:TUIBTransaction read GetTransaction write SetTransaction;
property SQLSelect:TStrings read GetSQLSelect write SetSQLSelect;
property SQLRefresh:TStrings read GetSQLRefresh write SetSQLRefresh;
property SQLEdit:TStrings read GetSQLEdit write SetSQLEdit;
property SQLDelete:TStrings read GetSQLDelete write SetSQLDelete;
property SQLInsert:TStrings read GetSQLInsert write SetSQLInsert;
property QuerySelect:TUIBQuery read FQuerySelect;
property QueryRefresh:TUIBQuery read FQueryRefresh;
property QueryInsert:TUIBQuery read FQueryInsert;
property QueryEdit:TUIBQuery read FQueryEdit;
property QueryDelete:TUIBQuery read FQueryDelete;
property Params: TSQLParams read GetParams;
property Option:TFBDsOptions read FOption write SetOption;
property AutoUpdateOptions:TAutoUpdateOptions read FAutoUpdateOptions write SetAutoUpdateOptions;
property MacroChar: Char read FMacroChar write SetMacroChar default DefaultMacroChar;
property Macros: TFBParams read GetMacros write SetMacros;
property MasterScrollBehavior:TMasterScrollBehavior read FMasterScrollBehavior write FMasterScrollBehavior default msbCancel;
property UpdateTransaction:TUIBTransaction read GetUpdateTransaction write SetUpdateTransaction {$IFNDEF FPC} stored StoreUpdateTransaction {$ENDIF FPC};
property OnFetchRecord:TNotifyEvent read FOnFetchRecord write FOnFetchRecord;
property UpdateRecordTypes: TFBUpdateRecordTypes read FUpdateRecordTypes
write SetUpdateRecordTypes;
//create the valid cache cell 4 required mode if possible, true if cell is exist
//(UTF8-RU-ansi) создает ячейку кеша блоба по заданому режиму доступа, true - если кеш существует,
// результат в BLOBRec
function BlobCacheMaintain(Field: TField; Mode: TBlobStreamMode;
var BLOBRec : TBLOBFieldData
) : boolean;
function GetMemo(Field: TField) : AnsiString;
procedure SetMemo(Field: TField; Value: AnsiString);
protected
{ ************** LocalIndexes interface *******************}
FLocalIndexes : THashedStringList;
{raise exception EIndexNotFound if not found}
function GetLocalIndex(const NameOrDef : string) : TRecordsBufferIndex;
{same as GetLocalIndex but return nil if not found}
function FindLocalIndex(const NameOrDef : string) : TRecordsBufferIndex;
function NewLocalIndex(const NameOrDef : string) : TRecordsBufferIndex;virtual;
{free index if it try to be assigned with nil}
procedure FreeLocalIndex(const NameOrDef : string; const Value : TRecordsBufferIndex);
procedure FreeLocalIndexes;
property LocalIndexes[const NameOrDef : string] : TRecordsBufferIndex read GetLocalIndex write FreeLocalIndex;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override;
function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override;
procedure ApplyUpdates;
function CachedUpdateStatus: TCachedUpdateStatus;
procedure CancelUpdates;
procedure CloseOpen(AFetchAll:boolean = false);
procedure FetchAll;
procedure FetchNext(FCount:integer);
procedure SortOnField(FieldName:string; Asc:boolean);
procedure SortOnFields(FieldNames:string; Asc: array of boolean);
procedure ExpandMacros;
function MacroByName(const AValue: string): TFBParam;
function Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean;override;
function Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant;overload;override;
function Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: array of TField): Variant;overload;virtual;
function UpdateStatus: TUpdateStatus; override;
procedure SetFieldValues(const ValueFields : array of TField; const Values : variant); overload;
procedure SetFieldValues(const ValueFields : string; const Values : variant); overload;
procedure SetFieldValues(Target : PRecordBuffer; const ValueFields : array of TField; const Values : variant); overload;
procedure SetFieldValues(Target : PRecordBuffer; const ValueFields : string; const Values : variant); overload;
procedure GetFieldValues(const ResultFields : array of TField; var Values : variant); overload;
procedure GetFieldValues(const ResultFields : string; var Values : variant); overload;
procedure GetFieldValues(Source : PRecordBuffer; const ResultFields : array of TField; var Values : variant); overload;
procedure GetFieldValues(Source : PRecordBuffer; const ResultFields : string; var Values : variant); overload;
function CurRecordCachedUpdateStatus:TCachedUpdateStatus; deprecated 'use UpdateStatus instead';
property MacroCount: Word read GetMacroCount;
property FetchedRecordCount:integer read FRecordCount;
//
procedure CloneRecord(SrcRecord: integer; IgnoreFields: array of const);
procedure CloneCurRecord(IgnoreFields: array of const);
property MemoValue[Field: TField] : AnsiString read GetMemo write SetMemo;
property RefreshTransactionKind:TTransactionKind read FRefreshTransactionKind write SetRefreshTransactionKind default
{$IFDEF OLD_REFRESH_TRAN_PARAMS}
tkDefault
{$ELSE}
tkReadTransaction
{$ENDIF}
;
{$IFDEF FB_USE_LCL}
property SQLScreenCursor :TCursor read FSQLScreenCursor write FSQLScreenCursor default crDefault;
{$ENDIF}
published
{if Memo size less than this value - it stores in memoty in native way - as string}
{(UTF8-RU-ansi) если размер Мемо меньше заданного значения - оно храница в виде строки иначе только в потоке}
// property MaxMEMOStringSize : cardinal read FMaxMEMOStringSize write FMaxMEMOStringSize default 16384;
end;
TRecBuf = class
private
FBufSize : cardinal;
FCurrent : PChar;
FOriginal : PChar;
function GetOriginal: PChar;
public
constructor Create(ABufSize:cardinal);
destructor Destroy; override;
procedure Modify;
property Current : PChar read FCurrent;
property Original: PChar read GetOriginal;
end;
{ TRecordsBuffer }
SaveCacheList = class;
TRecordsBuffer = class(TList)
protected
FOwner:TFBCustomDataSet;
function CompareField(Item1, Item2:PRecordBuffer; FieldNo:integer; Asc:Boolean):integer;
procedure SetUpdStatusFlag(Item:PRecordBuffer; Status:TCachedUpdateStatus);
function FindBufferByBookmark(ABookmark:Integer):PRecordBuffer;
public
{(UTF8-RU-ansi) счетчик изменений - используется индексами как идикатор устаревания}
ModifyStamp : cardinal;
constructor Create(AOwner:TFBCustomDataSet);
destructor Destroy; override;
procedure ReadRecordFromQuery(RecNo:integer; Sourse:TUIBQuery);
procedure RefreshRecordFromQuery(RecNo:integer; Sourse:TUIBQuery);
procedure SaveToBuffer(RecNo:integer; Buffer:PChar); //Ситаем из колекции в бувер датасета
procedure SaveFromBuffer(RecNo:integer; Buffer:PChar); //Запомним в колекции - Post
procedure SaveFromBufferI(RecNo:integer; Buffer:PChar); //Запомним в колекции - Insert
procedure SaveFromBufferA(RecNo:integer; Buffer:PChar); //Запомним в колекции - Append
procedure Clear;override;
procedure SortOnField(FieldNo:integer; Asc:boolean);
procedure SortOnFields(const SortArray:TFBInternalSortArray;const CountEl:integer);
procedure DeleteRecord(RecNo:integer);
procedure EditRecord(RecNo:integer; NewBuffer : PRecordBuffer);
procedure SaveCache(const Dest : SaveCacheList);
procedure LoadCache(const Dest : SaveCacheList);
end;
TFBDataSet = class(TFBCustomDataSet)
public
property Params;
property QuerySelect;
property QueryRefresh;
property QueryInsert;
property QueryEdit;
property QueryDelete;
published
property AfterRefresh;
property BeforeRefresh;
property AllowedUpdateKinds;
property AutoCommit;
property AutoUpdateOptions;
property DataSource;
property DefaultFormats;
property DetailConditions;
property Filtered;
property CachedUpdates;
property DataBase;
property Description;
property MacroChar;
property Macros;
property MasterScrollBehavior;
property Option;
property RefreshTransactionKind;
property Transaction;
property UpdateTransaction;
property UpdateRecordTypes;
property SQLSelect;
property SQLRefresh;
property SQLEdit;
property SQLDelete;
property SQLInsert;
{$IFDEF FB_USE_LCL}
property SQLScreenCursor;
{$ENDIF}
//Events
property OnUpdateRecord;
property OnUpdateError;
property OnFetchRecord;
// property MaxMEMOStringSize;
end;
TCacheState = (csNotReady, csFresh, csModified, csLoadBLOB, csStoreBLOB);
TBlobCacheStream = class(TBLOBCache)
protected
FState : tCacheState;
procedure DoWriteBlob;virtual;abstract;
procedure DoReadBlob;virtual;abstract;
procedure EnModifyValue;virtual;
function GetSize: Int64; override;
procedure SetText(const Src : AnsiString);virtual;
function GetText : AnsiString;virtual;
public
DS : TFBCustomDataSet;
Isc : TIscQuad;
constructor Create(aDS : TFBCustomDataSet; aOriginISC : TIscQuad);
destructor Destroy;override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
procedure SetSize(NewSize: Longint); override;
function Modified : boolean;
function New : TBlobCacheStream;virtual;abstract;
function Clone : TBlobCacheStream;virtual;
{(UTF8-RU-ansi) отсылает содержимое на сервер, если оно изменено, обновляет Isc}
procedure Flush;
{(UTF8-RU-ansi) загружает содержимо БЛОБА с сервера}
procedure Refresh;
{(UTF8-RU-ansi) делает кеш устаревшим}
procedure OutDate;
{(UTF8-RU-ansi) ускоряет создание кеша - если текущий кеш неразделяем то переинициирует себя
и себя же возвращает, иначе создает новый кеш его и возвращает }
function Change(const aIsc : tISCQuad) : TBLOBCache;
{(UTF8-RU-ansi) тоже только если текущий кеш разделеяем - то новый не создает а возвращает нил}
function ChangeOrNil(const aIsc : tISCQuad) : TBLOBCache;
property AnsiText : AnsiString read GetText write SetText;
end;
TFBBlobStream = class(TBlobCacheStream) {TBLOBCache}
protected
procedure DoWriteBlob;override;
procedure DoReadBlob;override;
public
function New : TBlobCacheStream;override;
end;
{ TFBAnsiMemoStream }
TFBAnsiMemoStream = class(TFBBlobStream)
protected
FMemoText : AnsiString;
FTextShared : boolean;
{(UTF8-RU-ansi) флаг устанавливается после чтения текста и сбрасывается после дублирования содержимого}
procedure EnModifyValue;override;
procedure SetText(const Src : AnsiString);override;
function GetText : AnsiString;override;
function Realloc(var NewCapacity: PtrInt): Pointer; override; //virtual;
public
constructor Create(aDS : TFBCustomDataSet; aOriginISC : TIscQuad);
destructor Destroy;override;
function New : TBlobCacheStream;override;
function Clone : TBlobCacheStream;override;
end;
TLostBLOBCacheEvent = procedure(const DSname : string; var List : TDSBLOBCacheList);
SaveCacheList = class(TList)
protected
IsSorted : boolean;
procedure Notify(Ptr: Pointer; Action: TListNotification); overload;
public
procedure Sort; overload;
function Locate(const ISQ : TIscQuad) : TBLOBCacheStream;
end;
TSaveCacheList = SaveCacheList;
{******************************************************************************
FLocalIndexes
*******************************************************************************}
FBRecordCompare = function(var context ;
{OwnerDS : TFBCustomDataSet;}
valA, valB : PRecordBuffer) : integer;
FBRecordCompareMethod = function(
{OwnerDS : TFBCustomDataSet;}
valA, valB : PRecordBuffer) : integer of object;
iRecordComparer = interface{class(TObject)}
function Compare(valA, valB : PRecordBuffer) : integer; overload;
function Compare(A : PRecordBuffer; const Value : variant) : integer; overload;
procedure Sort(var Records : TRecordsBuffer);
function Locate(const Records : tRecordsBuffer; const Values : variant) : TBookmark;
{
function Min(valA, valB : PRecordBuffer) : PRecordBuffer; overload; virtual;
function Max(valA, valB : PRecordBuffer) : PRecordBuffer; overload; virtual;
function Min(valA, valB : PRecordBuffer; AIndex, BIndex : integer): integer; overload; virtual;
function Max(valA, valB : PRecordBuffer; AIndex, BIndex : integer): integer; overload; virtual;
}
end;
TRecBufStamp = cardinal;
RBIFieldDef = record
FieldName : AnsiString;
Descendent : boolean;
CaseSence : boolean;
PartialKey : boolean;
AsPrefix : boolean;
end;
RBITask = Array of RBIFieldDef;
TLocalIndex = TList;
TRecordsBufferIndex = class(TLocalIndex)
protected
FOwner : TFBCustomDataSet;
FName : string;
Source : TRecordsBuffer;
ModifyStamp : TRecBufStamp;
SCompare : FBRecordCompare;
SLookup : FBRecordCompare;
Structure : RBITask;
FDefinition : AnsiString;
function Obsolete : boolean;
procedure SetName(const Value : string);
procedure SetDefinition(const aDef : string);overload;
{function Compare(valA, valB : PRecordBuffer) : integer; overload;virtual;abstract;
function Compare(A : PRecordBuffer; const Value : variant) : integer; overload;virtual;abstract;
}
function CompareRec(valA, valB : PRecordBuffer) : integer;virtual;abstract;
public
{for the named indexes}
property Name : string read FName write SetName;
property Definition : string read FDefinition write SetDefinition;
procedure SetDefinition(const aDef : TIndexDef);overload;
procedure Rebuild;virtual;abstract;
procedure DoFresh;
procedure Sort;overload;virtual;
{output the finest Record at least}
function SearchRec(const Values : variant; out Target : PRecordBuffer) : boolean;virtual;abstract;
function Locate(const Values : variant) : TBookmark;
function LocateRec(const Values : variant) : PRecordBuffer;virtual;abstract;
constructor Create({const aDefinition : String;} AOwner:TFBCustomDataSet);
destructor Destroy;override;
end;
FBRBICompareContext = record
FieldNo,
FieldOffset,
NullOffset,
FieldSize : cardinal;
DataHigh : cardinal;
Descending : boolean;
{компаратор FCompare используется методом Sort при построении индекса, FLookup используется методами
Locate и Lookup для поиска по сортироаному списку - поэтому они могут быть проще с менее глубоким
сравнением}
FCompare : FBRecordCompare;
FLookup : FBRecordCompare;
end;
RBIDefines = array of FBRBICompareContext;
TUniversalRBIndex = class(TRecordsBufferIndex)
protected
FFields: Array of TField;
FCompDefines : RBIDefines;
{FCompSpecDefines - эти компараторы используются при сравнении CompareRec для более глубокого сравнения
но не используются в LookupRec - это позволит использовать более точный индекс для новых менее
точных поисков}
FCompSpecDefines : RBIDefines;
function CompareRec(valA, valB : PRecordBuffer) : integer;override;
function LookupRec(valA, valB : PRecordBuffer) : integer;virtual;
public
constructor Create(const aDefinition : TIndexDef; AOwner:TFBCustomDataSet);overload;
constructor Create(const aDefinition : String; AOwner:TFBCustomDataSet);overload;
destructor Destroy;override;
procedure Rebuild;override;
function SearchRec(const Values : variant; out Target : PRecordBuffer) : boolean;override;
function LocateRec(const Values : variant) : PRecordBuffer;override;
end;
var
DefFBDsOptions : TFBDsOptions = [poTrimCharFields, poRefreshAfterPost];
OnLostBLOBCache : tLostBLOBCacheEvent = nil;
type
EIndexNotFound = class(exception);
EUnsupportedCompare = class(exception);
implementation
uses Math,
{$IFDEF FPC}
dbconst, LResources
{$ELSE}
dbconsts
{$ENDIF}
, sysConst
, variants
;
{$include FBRecord.inc}
{grow Dest array for 1 value and set one to a last array cell, returns an length of Dest}
function AppendItem( var Dest : IntegersArray; Value : integer) : integer;
begin
SetLength(Dest, Length(Dest) + 1);
result := Length(Dest);
Dest[result-1] := Value;
end;
type
PMEMOString = AnsiString;
{(UTF8-RU-ansi) ета запись используется для хранения БЛОБА в буфере записи}
{ this record use for store BLOB in RecordBuffer}
PBLOBRecordData = ^TBLOBRecordData;
TBLOBRecordData = record
IscQuad : TIscQuad;
ListIdx : cardinal;
end;
{*********************************************************************
TBlobWrapStream
this stream used to access to BLOB cache
(UTF8-RU-ansi) етот поток используется как посредник с кешем БЛОБа
*********************************************************************}
TBlobWrapStream = class(TStream)
protected
FField: TField;
FBlobStream: TBlobCacheStream;
protected
function GetSize: Int64; override;
public
Mode: TBlobStreamMode;
constructor Create(AField: TField; ABlobStream: TBlobCacheStream;
aMode: TBlobStreamMode);
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
procedure SetSize(NewSize: Longint); override;
function Write(const Buffer; Count: Longint): Longint; override;
end;
constructor TBlobWrapStream.Create(AField: TField; ABlobStream: TBlobCacheStream;
aMode: TBlobStreamMode);
begin
inherited Create;
FField := AField;
FBlobStream := ABlobStream;
Mode := aMode;
if (Mode = bmWrite) then
FBlobStream.SetSize(0)
else
FBlobStream.Position := 0;
end;
function TBlobWrapStream.Read(var Buffer; Count: Longint): Longint;
begin
result := FBlobStream.Read(Buffer, Count);
end;
function TBlobWrapStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
result := FBlobStream.Seek(Offset, Origin);
end;
function TBlobWrapStream.GetSize: Int64;
begin
result := FBlobStream.Size;
end;
procedure TBlobWrapStream.SetSize(NewSize: Longint);
begin
if not (Mode in [bmWrite, bmReadWrite]) then
FBErrorStr(fbeBlobCannotBeWritten);
FBlobStream.SetSize(NewSize);
{ TFBCustomDataSet(FField.DataSet).DataEvent(deFieldChange, Longint(FField));}
end;
function TBlobWrapStream.Write(const Buffer; Count: Longint): Longint;
begin
if not (Mode in [bmWrite, bmReadWrite]) then
FBErrorStr(fbeBlobCannotBeWritten);
result := FBlobStream.Write(Buffer, Count);
{TFBDataSet(FField.DataSet).RecordModified(True);}
{ TFBCustomDataSet(FField.DataSet).DataEvent(deFieldChange, Longint(FField));}
end;
{*********************************************************************
this stream used to wrap access to null BLOB
(UTF8-RU-ansi) етот поток используется как пустой БЛОБ, использую для избежания
лишней работы по управлению кешем для пустых полей
*********************************************************************}
type
TNullBlobWrapStream = class(TStream)
protected
function GetSize: Int64; override;
public
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
procedure SetSize(NewSize: Longint); override;
function Write(const Buffer; Count: Longint): Longint; override;
end;
function TNullBLOBWrapStream.GetSize: Int64;
begin
result := 0;
end;
function TNullBLOBWrapStream.Read(var Buffer; Count: Longint): Longint;
begin
result := 0;
end;
function TNullBLOBWrapStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
result := 0;
end;
procedure TNullBLOBWrapStream.SetSize(NewSize: Longint);
begin
FBErrorStr(fbeBlobCannotBeWritten);
end;
function TNullBLOBWrapStream.Write(const Buffer; Count: Longint): Longint;
begin
FBErrorStr(fbeBlobCannotBeWritten);
Write := 0;
end;
const
parPrefixNew = 'NEW_';
parPrefixOLD = 'OLD_';
{ TFieldsHeader }
function TFieldsHeader.GetFieldHeader(Index: Integer): TFieldHeader;
begin
Result:=TFieldHeader(Items[Index])
end;
procedure TFieldsHeader.Notify(Ptr: Pointer; Action: TListNotification);
var
P:TFieldHeader absolute Ptr;
begin
if Action = lnDeleted then
FreeAndNil(P);
end;
function TFieldsHeader.HeaderByName(AName: string): TFieldHeader;
var
i: Integer;
begin
AName:=UpperCase(AName);
Result:=nil;
for i:=0 to Count-1 do
if UpperCase(TFieldHeader(Items[I]).FieldName) = AName then
begin
Result:=TFieldHeader(Items[I]);
exit;
end;
end;
{ TFBCustomDataSet }
procedure TFBCustomDataSet.ApplyUpdates;
var
CurBookmark: TBookmark;
FUpdateAction: TUpdateAction;
UpdateKind: TUpdateKind;
bRecordsSkipped: Boolean;
i, rc: integer;
RecBuff:PRecordBuffer;
CurUpdateTypes:TFBUpdateRecordTypes;
begin
if not FCachedUpdates then
FBError(fbeNotCachedUpdates, [Name]);
if State in [dsEdit, dsInsert] then Post;
if FRecordCount = 0 then Exit;
DisableControls;
{$IFDEF NoAutomatedBookmark}
CurBookmark := GetBookmark;
{$ELSE}
CurBookmark := Bookmark;
{$ENDIF}
CurUpdateTypes := FUpdateRecordTypes;
FUpdateRecordTypes := [cusModified, cusInserted, cusDeleted];
try
UpdateStart;
First;
i := 1;
rc := FRecordCount;
bRecordsSkipped :=Eof ;
while (i <= rc) and not Eof do
begin
Inc(i);
RecBuff:=@(PRecordBuffer(GetActiveBuf)^);
case RecBuff^.CachedUpdateStatus of
cusModified: UpdateKind := ukModify;
cusInserted: UpdateKind := ukInsert;
else
UpdateKind := ukDelete;
end;
//if assigned manual updater - try it
if (Assigned(FOnUpdateRecord)) then
begin
FUpdateAction := uaFail;
FOnUpdateRecord(Self, UpdateKind, FUpdateAction);
end
else
FUpdateAction := uaRetry;
bRecordsSkipped := False;
case FUpdateAction of
uaFail: FBError(fbeUserAbort, []);
uaAbort: SysUtils.Abort;
uaApplied:
begin
RecBuff^.CachedUpdateStatus := cusUnmodified;
FRecordsBuffer.SaveFromBuffer(RecBuff^.Bookmark, GetActiveBuf);
end;
uaSkip:
bRecordsSkipped := True;
end;
if not bRecordsSkipped then
begin
while (FUpdateAction in [uaRetry]) do
begin
try
case RecBuff^.CachedUpdateStatus of
cusModified: InternalSaveRecord(QueryEdit, GetActiveBuf);
cusInserted: InternalSaveRecord(QueryInsert, GetActiveBuf);
cusDeleted: InternalSaveRecord(QueryDelete, GetActiveBuf);
end;
FUpdateAction := uaApplied;
if RecBuff^.CachedUpdateStatus = cusDeleted then
FRecordsBuffer.SetUpdStatusFlag(RecBuff, cusDeletedApplied)
// RecBuff^.CachedUpdateStatus:=cusDeletedApplied
else
FRecordsBuffer.SetUpdStatusFlag(RecBuff, cusUnmodified);
// RecBuff^.CachedUpdateStatus:=cusUnmodified;
except
on E: EFBError do