-
Notifications
You must be signed in to change notification settings - Fork 58
/
FIBMiscellaneous.pas
2275 lines (2070 loc) · 57.4 KB
/
FIBMiscellaneous.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
{***************************************************************}
{ FIBPlus - component library for direct access to Firebird and }
{ InterBase databases }
{ }
{ FIBPlus is based in part on the product }
{ Free IB Components, written by Gregory H. Deatz for }
{ Hoagland, Longo, Moran, Dunst & Doukas Company. }
{ mailto:[email protected] }
{ }
{ Copyright (c) 1998-2013 Devrace Ltd. }
{ Written by Serge Buzadzhy ([email protected]) }
{ }
{ ------------------------------------------------------------- }
{ FIBPlus home page: http://www.fibplus.com/ }
{ FIBPlus support : http://www.devrace.com/support/ }
{ ------------------------------------------------------------- }
{ }
{ Please see the file License.txt for full license information }
{***************************************************************}
unit FIBMiscellaneous;
interface
{$I FIBPlus.inc}
uses
{$IFDEF WINDOWS}
Windows, // For Inline functions
{$ENDIF}
SysUtils,SyncObjs, Classes, ibase,IB_Intf,IB_Externals,
DB, fib, FIBDatabase, FIBQuery, StdFuncs,IB_ErrorCodes,FIBPlatforms ;
const
DefaultBlobSegmentSize = High(Word);
type
(* TFIBBlobStream *)
TFIBBlobStream = class(TStream)
private
FDatabase:TFIBDatabase;
FTransaction:TFIBTransaction;
FUpdateTransaction:TFIBTransaction;
FBlobID: TISC_QUAD;
FBlobMaxSegmentSize, // Maximum segment size
FBlobNumSegments, // How many segments?
FBlobSize: Long; // Blob size
FOldBlobSize: Long;
FBlobType: Short; // 0 = segmented, 1 = streamed.
FBlobSubType: Long; // ivan_ra
FBuffer: PAnsiChar;
FOldBuffer: PAnsiChar;
FBlobInitialized: Boolean; // Has the blob been "opened" yet?
FBlobHandle: TISC_BLOB_HANDLE;
FMode: TBlobStreamMode; // (bmRead, bmWrite, bmReadWrite);
FModified: Boolean; // When finalize is called, does it need to do anything?
FPosition: Long; // The current position in the stream.
FBlobStreamList:TList;
FIndexInList:integer;
FFieldNo :integer;
FNeedSaveOldBuffer :boolean;
FTableName:Ansistring;
FFieldName:Ansistring;
FKeyValues:TDynArray;
FLoadedFromCache:boolean;
FIsClientField:boolean;
FCharSet:integer;
function GetUpdateTRHandle: PISC_TR_HANDLE;
function GetRecKeyValuesAsStr:string;
protected
procedure DoOnDatabaseFree(Sender:TObject);
procedure CreateBlob;
procedure EnsureBlobInitialized(CallBack:TCallBackBlobReadWrite=nil);
procedure GetBlobInfo;
function GetDatabase: TFIBDatabase;
function GetDBHandle: PISC_DB_HANDLE;
function GetTransaction: TFIBTransaction;
function GetUpdateTransaction: TFIBTransaction;
function GetTRHandle: PISC_TR_HANDLE;
procedure CheckHandles(ReadTransaction:boolean=True);
procedure OpenBlob(CallBack:TCallBackBlobReadWrite=nil);
procedure SetBlobID(const Value: TISC_QUAD);
procedure ReplaceBlobID(const Value: TISC_QUAD);
procedure SetDatabase(Value: TFIBDatabase);
procedure SetMode(Value: TBlobStreamMode);
procedure SetTransaction(Value: TFIBTransaction);
procedure SetUpdateTransaction(Value: TFIBTransaction);
function GetAsString: Ansistring;
function GetAsWideString: Widestring;
procedure SaveOldBuffer;
public
constructor CreateNew(aFieldNo:integer;aBlobStreamList:TList;
const aTableName:string = '';
const aFieldName:string = '';
PKeyValues:PDynArray=nil
);
constructor Create;
procedure InternalSetCharSet(Value:integer); // Internal Use only
destructor Destroy; override;
function Call(ErrCode: ISC_STATUS; RaiseError: Boolean): ISC_STATUS;
procedure CheckReadable;
procedure CheckWritable;
procedure DoFinalize(ClearModified, ForceWrite:Boolean;CallBack:TCallBackBlobReadWrite=nil);
procedure Finalize;
procedure CloseBlob;
procedure Cancel;
procedure FreeOldBuffer;
procedure DeInitialize;
function LoadFromFile(const Filename: string;IsCacheFile:boolean=False):boolean;
function LoadFromStream(Stream: TStream;IsCacheStream:boolean=False):boolean;
function Read(var Buffer; Count: Longint): Longint; override;
function ReadOldBuffer(var Buffer; Count: Longint): Longint;
function GenerateSwapFileName(ForceDir:boolean):string;
procedure SaveToSwapFile;
procedure SaveToFile(const Filename: string;FullInfo:boolean=False);
procedure SaveToStream(Stream: TStream;IsCacheStream:boolean=False);
function Seek(Offset: Longint; Origin: Word): Longint; override;
function DoSeek(Offset: Longint; Origin: Word;CallBack:TCallBackBlobReadWrite): Longint;
function SeekInOldBuffer(Offset: Longint; Origin: Word): Longint;
procedure SetSize(NewSize: Long); override;
procedure Truncate;
function Write(const Buffer; Count: Longint): Longint; override;
//For Big Blobs
function FileToBlob(const FileName:string;CallBack:TCallBackBlobReadWrite=nil):TISC_QUAD;
procedure BlobToFile(const FileName:string;CallBack:TCallBackBlobReadWrite=nil);
// properties
property BlobInitialized:boolean read FBlobInitialized;
property Handle: TISC_BLOB_HANDLE read FBlobHandle;
property BlobHandle: TISC_BLOB_HANDLE read FBlobHandle;
property BlobID: TISC_QUAD read FBlobID write SetBlobID;
property BlobMaxSegmentSize: Long read FBlobMaxSegmentSize;
property BlobNumSegments: Long read FBlobNumSegments;
property BlobSize: Long read FBlobSize;
property BlobType: Short read FBlobType;
property BlobSubType: Long read FBlobSubType write FBlobSubType; // ivan_ra
property Database: TFIBDatabase read GetDatabase write SetDatabase;
property DBHandle: PISC_DB_HANDLE read GetDBHandle;
property Mode: TBlobStreamMode read FMode write SetMode;
property Modified: Boolean read FModified;
property Transaction: TFIBTransaction read GetTransaction write SetTransaction;
property UpdateTransaction: TFIBTransaction read GetUpdateTransaction write SetUpdateTransaction;
property TRHandle: PISC_TR_HANDLE read GetTRHandle;
property UpdateTRHandle: PISC_TR_HANDLE read GetUpdateTRHandle;
property AsString:Ansistring read GetAsString;
property AsWideString:Widestring read GetAsWideString;
property FieldNo :integer read FFieldNo;
property IndexInList:integer read FIndexInList;
property FieldName:Ansistring read FFieldName write FFieldName;
property TableName:Ansistring read FTableName write FTableName;
property RecordKeyValues:TDynArray read FKeyValues write FKeyValues;
property IsClientField:boolean read FIsClientField write FIsClientField;
end;
// Blob routine functions
TBlobInfo= record
NumSegments, MaxSegmentSize, TotalSize: Long;
BlobType :Short;
end;
function GetBlobInfoRec(DB:TFIBDatabase; TR:TFIBTransaction;blob_id : TISC_QUAD; var Success :boolean ):TBlobInfo;
procedure GetBlobInfo(ClientLibrary:IIbClientLibrary; hBlobHandle: PISC_BLOB_HANDLE;
var NumSegments, MaxSegmentSize, TotalSize: Long; var BlobType: Short);
procedure ReadBlob(ClientLibrary:IIbClientLibrary; hBlobHandle: PISC_BLOB_HANDLE; var Buffer: PAnsiChar;
var BlobSize: Long;CallBack:TCallBackBlobReadWrite=nil);
procedure WriteBlob(ClientLibrary:IIbClientLibrary; hBlobHandle: PISC_BLOB_HANDLE; Buffer: PAnsiChar;
BlobSize: Long;CallBack:TCallBackBlobReadWrite=nil);
function BlobExist(ClientLibrary:IIbClientLibrary; DBHandle:TISC_DB_HANDLE;
TRHandle:TISC_TR_HANDLE;blob_id : TISC_QUAD
):boolean;
function FileToBlob(const FileName:string;Database:TFIBDatabase;Transaction:TFIBTransaction;
cb: TCallBackBlobReadWrite
):TISC_QUAD;
procedure BlobToFile(BlobID:TISC_QUAD;const FileName:string;Database:TFIBDatabase;Transaction:TFIBTransaction;
cb: TCallBackBlobReadWrite
);
type
(* TFIBOutputDelimitedFile *)
TFIBFileOutputStream= class(TFIBBatchOutputStream)
protected
FFile:TFileStream;
FBuffer:PAnsiChar;
FBuffPos:integer;
procedure CloseFile;
procedure FlushBuf(Force:boolean; Count:integer);
function WriteValue(const ValBuffer; Count: Longint):Integer;
public
constructor Create;
destructor Destroy; override;
end;
TFIBOutputDelimitedFile = class(TFIBFileOutputStream)
protected
// FFile:TFileStream;
FOutputTitles: Boolean;
FColDelimiter,
FRowDelimiter: string;
st :string;
val: string;
procedure CloseFile;
{ procedure PrepareBuffer;
procedure FlushBuf(Force:boolean; Count:integer);
function WriteValue(const ValBuffer; Count: Longint):Integer;}
public
procedure ReadyStream; override;
function WriteColumns: Boolean; override;
property ColDelimiter: string read FColDelimiter write FColDelimiter;
property OutputTitles: Boolean read FOutputTitles
write FOutputTitles;
property RowDelimiter: string read FRowDelimiter write FRowDelimiter;
end;
(* TFIBInputDelimitedFile *)
TFIBInputDelimitedFile = class(TFIBBatchInputStream)
protected
FColDelimiter,
FRowDelimiter: string;
FEOF: Boolean;
FFile: TFileStream;
FLookAhead: Char;
FReadBlanksAsNull: Boolean;
FSkipTitles: Boolean;
public
destructor Destroy; override;
function GetColumn(var Col: AnsiString): Integer;
function ReadParameters: Boolean; override;
procedure ReadyStream; override;
property ColDelimiter: string read FColDelimiter write FColDelimiter;
property ReadBlanksAsNull: Boolean read FReadBlanksAsNull
write FReadBlanksAsNull;
property RowDelimiter: string read FRowDelimiter write FRowDelimiter;
property SkipTitles: Boolean read FSkipTitles write FSkipTitles;
end;
(* TFIBOutputRawFile *)
TFIBOutputRawFile = class(TFIBFileOutputStream)
public
constructor Create;
constructor CreateEx(aVersion:integer;const CharSet:string);
procedure ReadyStream; override;
function WriteColumns: Boolean; override;
end;
(* TFIBInputRawFile *)
TFIBInputRawFile = class(TFIBBatchInputStream)
protected
// FHandle: THandle;
FFile:TFileStream;
FMap:TList;
SkippedLen:array of integer;
procedure CloseFile;
public
destructor Destroy; override;
function ReadParameters: Boolean; override;
procedure ReadyStream; override;
end;
var
NullQUID:TISC_QUAD;
function EquelQUADs(const Value1,Value2:TISC_QUAD):boolean;
procedure ValidateBlobCacheDirectory(Database:TFIBDataBase);
implementation
uses
StrUtil,FIBDataSet,IBBlobFilter,FIBConsts
{$IFDEF MACOS}
,Posix.Unistd
{$ENDIF}
{$IFDEF D6+}
,Variants, pFIBProps
{$ENDIF}
;
function EquelQUADs(const Value1,Value2:TISC_QUAD):boolean;
begin
Result:=
(Value1.gds_quad_high=Value2.gds_quad_high)
and
(Value1.gds_quad_low=Value2.gds_quad_low)
end;
var
SwapVersion:integer=1;
BlobCacheSignature:Ansistring='FIB$BLOB_BODY';
BlobCacheOperation: TCriticalSection;
procedure DoValidateBlobCacheFile(Database:TFIBDataBase; Transaction:TFIBTransaction;const FileName:string);
var
Stream: TStream;
tmpStr:Ansistring;
tmpInt:integer;
tmpBlobId:TISC_QUAD;
vFileIsValid:boolean;
begin
vFileIsValid:=False;
BlobCacheOperation.Acquire;
try
Stream := TFileStream.Create(FileName, fmOpenRead);
try
Stream.Position := 0;
SetLength(tmpStr,Length(BlobCacheSignature));
Stream.Read(tmpStr[1],Length(BlobCacheSignature));
if tmpStr=BlobCacheSignature then
begin
Stream.Read(tmpInt,SizeOf(tmpInt));
if tmpInt=SwapVersion then
begin
Stream.Read(tmpBlobId,SizeOf(TISC_QUAD));
if not Transaction.DefaultDatabase.Connected then
Transaction.DefaultDatabase.Connected:=True;
if not Transaction.InTransaction then
Transaction.StartTransaction;
vFileIsValid:=
BlobExist(Database.ClientLibrary,
Database.Handle,Transaction.Handle,tmpBlobId
);
end;
end;
finally
Stream.Free;
end;
except
end;
try
if not vFileIsValid then
DeleteFile(FileName);
finally
BlobCacheOperation.Release;
end;
end;
procedure DoValidateBlobCacheDirectory(Database:TFIBDataBase; Transaction:TFIBTransaction; const Dir:string);
var
sr: TSearchRec;
FileAttrs: Integer;
begin
FileAttrs:=faAnyFile;
if FindFirst(Dir+'*.blb', FileAttrs, sr) = 0 then
begin
repeat
if (sr.Attr and FileAttrs) = sr.Attr then
begin
DoValidateBlobCacheFile(Database,Transaction,Dir+sr.Name);
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
FileAttrs:=faDirectory;
if FindFirst(Dir+'*', FileAttrs, sr) = 0 then
begin
repeat
if (sr.Attr and FileAttrs) = sr.Attr then
if (sr.Name<>'.') and (sr.Name<>'..') then
DoValidateBlobCacheDirectory(Database,Transaction,Dir+sr.Name+'\');
until FindNext(sr) <> 0;
FindClose(sr);
end;
end;
type
TValidateBlobCacheThread = class(TThread)
private
FDatabase:TFIBDataBase;
FTransaction:TFIBTransaction;
FCacheDir:string;
protected
procedure Execute; override;
public
constructor Create(Database:TFIBDataBase);
destructor Destroy; override;
end;
{ TValidateBlobCacheThread }
constructor TValidateBlobCacheThread.Create(Database: TFIBDataBase);
begin
FDatabase:=TFIBDatabase.Create(nil);
with FDatabase do
begin
if Database.IsRemoteConnect then
DBName :=Database.DBName
else
DBName :='localhost:'+Database.DBName;
DBParams:=Database.DBParams;
UseLoginPrompt:=False;
SynchronizeTime:=False;
Name:='dbValidateBlobCache';
LibraryName:=Database.LibraryName
// Connected:=True;
end;
FTransaction:=TFIBTransaction.Create(nil);
with FTransaction do
begin
DefaultDatabase:=FDatabase;
Name:='trValidateBlobCache';
TRParams.Add('read');
TRParams.Add('isc_tpb_nowait');
TRParams.Add('read_committed');
TRParams.Add('rec_version');
end;
FCacheDir:=Database.BlobSwapSupport.SwapDirectory;
FreeOnTerminate:=True;
inherited Create(False);
end;
destructor TValidateBlobCacheThread.Destroy;
begin
if FTransaction.InTransaction then
FTransaction.Commit;
FTransaction.Free;
FDatabase.Connected:=False;
FDatabase.Free;
inherited Destroy;
end;
procedure TValidateBlobCacheThread.Execute;
begin
DoValidateBlobCacheDirectory(FDatabase,FTransaction,FCacheDir);
end;
procedure ValidateBlobCacheDirectory(Database:TFIBDataBase);
begin
if not Assigned(Database) or not (Database.Connected)
or (Length(Database.BlobSwapSupport.SwapDirectory) = 0)
or not DirectoryExists(Database.BlobSwapSupport.SwapDirectory)
then
Exit;
TValidateBlobCacheThread.Create(Database);
end;
function GetBlobInfoRec(DB:TFIBDatabase;TR:TFIBTransaction; blob_id : TISC_QUAD;var Success :boolean ):TBlobInfo;
var
BlobHandle: TISC_BLOB_HANDLE;
begin
if not Assigned(DB) or not Assigned(TR) or not TR.Active then
begin
Success:=False; Exit;
end;
if not Assigned(DB.ClientLibrary) then
raise
EAPICallException.Create(Format(SUnknownClientLibrary,['GetBlobInfo']));
BlobHandle:=nil;
Success :=
DB.ClientLibrary.isc_open_blob2(
StatusVector, @DB.Handle, @TR.Handle, @BlobHandle,@blob_id, 0, nil)=0;
if Success then
with Result do
begin
GetBlobInfo(DB.ClientLibrary,@BlobHandle, NumSegments, MaxSegmentSize, TotalSize,BlobType);
DB.ClientLibrary.isc_close_blob(StatusVector,@BlobHandle)
end
else
FillChar(Result,SizeOf(Result),0);
end;
procedure GetBlobInfo(ClientLibrary:IIbClientLibrary; hBlobHandle: PISC_BLOB_HANDLE;
var NumSegments, MaxSegmentSize, TotalSize: Long; var BlobType: Short);
var
items: array[0..3] of AnsiChar;
results: array[0..99] of AnsiChar;
i, item_length: Integer;
item: Integer;
begin
if not Assigned(ClientLibrary) then
raise
EAPICallException.Create(Format(SUnknownClientLibrary,['GetBlobInfo']));
items[0] := AnsiChar(isc_info_blob_num_segments);
items[1] := AnsiChar(isc_info_blob_max_segment);
items[2] := AnsiChar(isc_info_blob_total_length);
items[3] := AnsiChar(isc_info_blob_type);
if ClientLibrary.isc_blob_info(StatusVector, hBlobHandle, 4, @items[0], SizeOf(results),
@results[0]) > 0 then
IBError(ClientLibrary,nil);
i := 0;
while (i < SizeOf(results)) and (results[i] <> AnsiChar(isc_info_end)) do
begin
item := Integer(results[i]); Inc(i);
item_length := ClientLibrary.isc_vax_integer(@results[i], 2); Inc(i, 2);
case item of
isc_info_blob_num_segments:
NumSegments := ClientLibrary.isc_vax_integer(@results[i], item_length);
isc_info_blob_max_segment:
MaxSegmentSize := ClientLibrary.isc_vax_integer(@results[i], item_length);
isc_info_blob_total_length:
TotalSize := ClientLibrary.isc_vax_integer(@results[i], item_length);
isc_info_blob_type:
BlobType := ClientLibrary.isc_vax_integer(@results[i], item_length);
end;
Inc(i, item_length);
end;
end;
procedure OldReadBlob(ClientLibrary:IIbClientLibrary; hBlobHandle: PISC_BLOB_HANDLE; var Buffer: PAnsiChar;
var BlobSize: Long;CallBack:TCallBackBlobReadWrite=nil);
var
BytesRead, SegLen: UShort;
LocalBuffer: PAnsiChar;
AllReadBytes:integer;
Stop:boolean;
begin
if not Assigned(ClientLibrary) then
raise
EAPICallException.Create(Format(SUnknownClientLibrary,['ReadBlob']));
LocalBuffer := Buffer;
if BlobSize<DefaultBlobSegmentSize then
SegLen:=BlobSize // Avoid IB2007 bug
else
SegLen := DefaultBlobSegmentSize;
AllReadBytes:=0;
Stop:=False;
while (AllReadBytes<BlobSize) do
begin
if (AllReadBytes + SegLen > BlobSize) then
SegLen :=BlobSize-AllReadBytes ;
if not ((ClientLibrary.isc_get_segment(
StatusVector, hBlobHandle, @BytesRead, SegLen,
LocalBuffer) = 0) or
(StatusVectorArray[1] = isc_segment)) then
IBError(ClientLibrary,nil);
Inc(LocalBuffer, BytesRead);
Inc(AllReadBytes,BytesRead);
if Assigned(CallBack) then
CallBack(BlobSize,AllReadBytes,Stop);
if Stop then
Exit;
end;
end;
procedure ReadBlob(ClientLibrary:IIbClientLibrary; hBlobHandle: PISC_BLOB_HANDLE; var Buffer: PAnsiChar;
var BlobSize: Long;CallBack:TCallBackBlobReadWrite=nil);
var
vBlobSize:Long;
BytesRead, SegLen: UShort;
LocalBuffer: PAnsiChar;
Stop:boolean;
begin
// Don't work correctly for FB1.5 local connect
if not Assigned(ClientLibrary) then
raise
EAPICallException.Create(Format(SUnknownClientLibrary,['ReadBlob']));
Stop:=False;
vBlobSize:=0;
LocalBuffer := Buffer;
while True do
begin
if vBlobSize=BlobSize then
SegLen:=0
else
if BlobSize<DefaultBlobSegmentSize then
SegLen:=BlobSize // Avoid IB2007 bug
else
SegLen := DefaultBlobSegmentSize;
case ClientLibrary.isc_get_segment(
StatusVector, hBlobHandle, @BytesRead, SegLen,
LocalBuffer) of
0,isc_segment:
begin
Inc(LocalBuffer, BytesRead);
Inc(vBlobSize,BytesRead);
if Assigned(CallBack) then
CallBack(BlobSize,vBlobSize,Stop);
if Stop then
Exit;
end;
isc_segstr_eof:
begin
if vBlobSize<BlobSize then
ReallocMem(Buffer,vBlobSize);
Inc(vBlobSize,BytesRead);
BlobSize:=vBlobSize;
if Assigned(CallBack) then
CallBack(BlobSize,vBlobSize,Stop);
Exit;
end
else
IBError(ClientLibrary,nil);
end;
end;
end;
procedure WriteBlob(ClientLibrary:IIbClientLibrary; hBlobHandle: PISC_BLOB_HANDLE; Buffer: PAnsiChar;
BlobSize: Long;CallBack:TCallBackBlobReadWrite=nil);
var
CurPos, SegLen: Long;
Stop:boolean;
begin
if not Assigned(ClientLibrary) then
raise
EAPICallException.Create(Format(SUnknownClientLibrary,['WriteBlob']));
Stop:=False;
CurPos := 0;
SegLen := DefaultBlobSegmentSize;
while (CurPos < BlobSize) do
begin
if (CurPos + SegLen > BlobSize) then
SegLen := BlobSize - CurPos;
if ClientLibrary.isc_put_segment(StatusVector, hBlobHandle, SegLen,
PAnsiChar(@Buffer[CurPos])) > 0 then
IBError(ClientLibrary,nil);
Inc(CurPos, SegLen);
if Assigned(CallBack) then
CallBack(BlobSize,CurPos,Stop);
if Stop then
begin
ClientLibrary.isc_cancel_blob(StatusVector, hBlobHandle);
Exit;
end;
end;
end;
function BlobExist(ClientLibrary:IIbClientLibrary; DBHandle:TISC_DB_HANDLE;
TRHandle:TISC_TR_HANDLE;blob_id : TISC_QUAD
):boolean;
var
BlobHandle: TISC_BLOB_HANDLE;
begin
if not Assigned(ClientLibrary) then
raise
EAPICallException.Create(Format(SUnknownClientLibrary,['BlobExist']));
BlobHandle:=nil;
Result:=
ClientLibrary.isc_open_blob2(
StatusVector, @DBHandle, @TRHandle, @BlobHandle,@blob_id, 0, nil)=0;
if Result then
ClientLibrary.isc_close_blob(StatusVector,@BlobHandle)
end;
function FileToBlob(const FileName:string;Database:TFIBDatabase;Transaction:TFIBTransaction;
cb: TCallBackBlobReadWrite
):TISC_QUAD;
var fs: TFIBBlobStream;
begin
fs := TFIBBlobStream.CreateNew(0, nil);
try
fs.Database := Database;
fs.Transaction := Transaction;
fs.Mode := bmReadWrite;
Result:=fs.FileToBlob(FileName,cb)
finally
fs.Free;
end;
end;
procedure BlobToFile(BlobID:TISC_QUAD;const FileName:string;Database:TFIBDatabase;Transaction:TFIBTransaction;
cb: TCallBackBlobReadWrite
);
var fs: TFIBBlobStream;
begin
fs := TFIBBlobStream.CreateNew(0, nil);
try
fs.Database := Database;
fs.Transaction := Transaction;
fs.Mode := bmRead;
fs.BlobID:=BlobID;
fs.BlobToFile(FileName,cb)
finally
fs.Free;
end;
end;
(* TFIBBlobStream *)
procedure TFIBBlobStream.DoOnDatabaseFree(Sender: TObject);
begin
FDatabase :=nil;
FTransaction:=nil;
end;
constructor TFIBBlobStream.CreateNew(aFieldNo:integer;aBlobStreamList:TList;
const aTableName:string='';
const aFieldName:string = '';
PKeyValues:PDynArray=nil
);
begin
inherited Create;
FCharSet :=-1;
FBuffer := nil;
FBlobSize := 0;
FOldBuffer := nil;
FOldBlobSize := 0;
FBlobInitialized:=false;
FBlobStreamList :=aBlobStreamList;
FFieldNo :=aFieldNo;
FNeedSaveOldBuffer :=True;
if Assigned(FBlobStreamList) then
FIndexInList:=FBlobStreamList.Add(Self);
FTableName:=aTableName;
FFieldName:=aFieldName;
if PKeyValues<>nil then
FKeyValues:=PKeyValues^
else
SetLength(FKeyValues,0);
end;
constructor TFIBBlobStream.Create;
begin
CreateNew(-1,nil)
end;
procedure TFIBBlobStream.InternalSetCharSet(Value:integer);
begin
FCharSet:=Value
end;
destructor TFIBBlobStream.Destroy;
begin
CloseBlob;
SetSize(0);
ReallocMem(FOldBuffer, 0);
FOldBuffer := nil;
FOldBlobSize := 0;
if Assigned(FBlobStreamList) then
with FBlobStreamList do
begin
begin
if FIndexInList<Count-1 then
begin
FBlobStreamList[FIndexInList]:=FBlobStreamList[Count-1];
TFIBBlobStream(FBlobStreamList[FIndexInList]).FIndexInList:=FIndexInList;
end;
Delete(Count-1)
end;
end;
inherited Destroy;
end;
function TFIBBlobStream.Call(ErrCode: ISC_STATUS; RaiseError: Boolean): ISC_STATUS;
begin
Result := 0;
if Transaction <> nil then
Result := Transaction.Call(ErrCode, RaiseError)
else
if RaiseError and (ErrCode > 0) then
IBError(FDatabase.ClientLibrary,Self);
end;
procedure TFIBBlobStream.CheckReadable;
begin
if FMode = bmWrite then FIBError(feBlobCannotBeRead, [nil]);
end;
procedure TFIBBlobStream.CheckWritable;
begin
if (FMode = bmRead) and not (IsClientField) then FIBError(feBlobCannotBeWritten, [nil]);
end;
procedure TFIBBlobStream.CloseBlob;
begin
if (FBlobHandle <> nil) and
(Call(FDatabase.ClientLibrary.isc_close_blob(StatusVector, @FBlobHandle), False) > 0) then
IBError(FDatabase.ClientLibrary,Self);
FBlobHandle:=nil;
FBlobInitialized:=false;
end;
procedure TFIBBlobStream.CreateBlob;
begin
CheckWritable;
FBlobID.gds_quad_high := 0;
FBlobID.gds_quad_low := 0;
Truncate;
end;
procedure TFIBBlobStream.EnsureBlobInitialized(CallBack:TCallBackBlobReadWrite=nil);
begin
if not FBlobInitialized then
if FIsClientField then
FBlobInitialized :=True
else
begin
case FMode of
bmWrite:
CreateBlob;
bmReadWrite:
begin
if (FBlobID.gds_quad_high = 0) and
(FBlobID.gds_quad_low = 0) then
CreateBlob
else
OpenBlob(CallBack);
end;
else
OpenBlob(CallBack);
end;
FBlobInitialized := True;
SaveToSwapFile;
end;
end;
{var
stream_bpb : array[0..2] of char = (Char(isc_bpb_version1),
Char(isc_bpb_type), Char(isc_bpb_type_stream)
);
}
procedure TFIBBlobStream.DoFinalize(ClearModified, ForceWrite:Boolean;CallBack:TCallBackBlobReadWrite=nil);
var
Temp:PAnsiChar;
SizeBeforeFilter:integer;
vFiltered:boolean;
begin
// ClearModified - don't need write. Change Cache to unmodified only
if (not FBlobInitialized) or (FMode = bmRead) or (not FModified and not ForceWrite) then
Exit;
FLoadedFromCache:=False;
if ClearModified then
begin
FNeedSaveOldBuffer:=True;
FModified := False;
Exit;
end;
CheckHandles(False);
// We need to start writing to a blob, so first create one.
Call(FDatabase.ClientLibrary.isc_create_blob2(StatusVector, DBHandle, UpdateTRHandle, @FBlobHandle,
@FBlobID, 0, nil), True);
vFiltered:=ExistBlobFilter(Database,FBlobSubType);
SizeBeforeFilter:=FBlobSize;
if vFiltered then
begin
Temp:=nil;
ReallocMem(Temp, FBlobSize);
Move(FBuffer[0], Temp[0], FBlobSize);
IBFilterBuffer(Database,FBuffer, FBlobSize, FBlobSubType, True);
end;
FIBMiscellaneous.WriteBlob(FDatabase.ClientLibrary,@FBlobHandle, FBuffer, FBlobSize,CallBack);
Call(FDatabase.ClientLibrary.isc_close_blob(StatusVector, @FBlobHandle), True);
if vFiltered then
begin
FBlobSize := SizeBeforeFilter;
FreeMem(FBuffer);
FBuffer :=Temp;
end;
if ClearModified then FModified := False;
end;
procedure TFIBBlobStream.Finalize;
begin
DoFinalize(False,False);
DoFinalize(True,False) ;
end;
procedure TFIBBlobStream.Cancel;
begin
if FBlobInitialized and Modified then
begin
SetSize(FOldBlobSize);
if FBlobSize>0 then
Move(FOldBuffer[0], FBuffer[0], FBlobSize);
FModified := False;
FNeedSaveOldBuffer:= True;
FreeMem(FOldBuffer);
FOldBuffer:=nil;
FOldBlobSize:=0;
end;
end;
procedure TFIBBlobStream.DeInitialize;
begin
FreeOldBuffer;
if FBlobSize>0 then
begin
SetSize(0);
FBlobInitialized:=False;
end;
end;
procedure TFIBBlobStream.FreeOldBuffer;
begin
if Assigned(FOldBuffer) then
begin
ReallocMem(FOldBuffer,0);
FOldBlobSize:=0;
end;
end;
procedure TFIBBlobStream.GetBlobInfo;
var
iBlobSize: Long;
begin
FIBMiscellaneous.GetBlobInfo(FDatabase.ClientLibrary,@FBlobHandle,
FBlobNumSegments, FBlobMaxSegmentSize, iBlobSize, FBlobType
);
SetSize(iBlobSize);
end;
function TFIBBlobStream.GetDatabase: TFIBDatabase;
begin
Result := FDatabase;
end;
function TFIBBlobStream.GetDBHandle: PISC_DB_HANDLE;
begin
if Assigned(FDatabase) and Assigned(FDatabase.Handle) then
Result := @FDatabase.Handle
else
Result :=nil;
end;
function TFIBBlobStream.GetTransaction: TFIBTransaction;
begin
Result := FTransaction;
end;
function TFIBBlobStream.GetUpdateTransaction: TFIBTransaction;
begin
if Assigned(FUpdateTransaction) then
Result := FUpdateTransaction
else
Result := FTransaction;
end;
function TFIBBlobStream.GetUpdateTRHandle: PISC_TR_HANDLE;
begin
if Assigned(FUpdateTransaction) then
Result := @FUpdateTransaction.Handle
else
Result := GetTRHandle
end;
function TFIBBlobStream.GetTRHandle: PISC_TR_HANDLE;
begin
if Assigned(FTransaction) and Assigned(FTransaction.Handle) then
Result := @FTransaction.Handle
else
Result := nil
end;
procedure TFIBBlobStream.CheckHandles(ReadTransaction:boolean=True);
begin
if (GetDBHandle=nil) then
begin
if not Assigned(Database) then
FIBError(feDatabaseNotAssigned, ['BlobStream'])
else
FIBError(feDatabaseClosed, ['BlobStream'])
end
else
if ReadTransaction then
begin
if (GetTRHandle=nil) then
begin
if not Assigned(Transaction) then
FIBError(feTransactionNotAssigned, ['BlobStream'])
else
FIBError(feNotInTransaction, ['BlobStream'])
end;
end
else
if (GetUpdateTRHandle=nil) then
begin
if not Assigned(FUpdateTransaction) then
FIBError(feTransactionNotAssigned, ['BlobStream'])
else
FIBError(feNotInTransaction, ['BlobStream'])
end;
end;
function TFIBBlobStream.LoadFromFile(const Filename: string;IsCacheFile:boolean=False):boolean;
var
Stream: TStream;
begin
BlobCacheOperation.Acquire;