forked from Sovos-Compliance/convey-public-libs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kbmMemCSVStreamFormat.pas
1536 lines (1379 loc) · 48.1 KB
/
kbmMemCSVStreamFormat.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
unit kbmMemCSVStreamFormat;
interface
{$include kbmMemTable.inc}
// =========================================================================
// CSV stream format for kbmMemTable v. 3.xx+
//
// Copyright 1999-2002 Kim Bo Madsen/Optical Services - Scandinavia
// All rights reserved.
//
// LICENSE AGREEMENT
// PLEASE NOTE THAT THE LICENSE AGREEMENT HAS CHANGED!!! 16. Feb. 2000
//
// You are allowed to use this component in any project for free.
// You are NOT allowed to claim that you have created this component or to
// copy its code into your own component and claim that it was your idea.
//
// -----------------------------------------------------------------------------------
// IM OFFERING THIS FOR FREE FOR YOUR CONVINIENCE, BUT
// YOU ARE REQUIRED TO SEND AN E-MAIL ABOUT WHAT PROJECT THIS COMPONENT (OR DERIVED VERSIONS)
// IS USED FOR !
// -----------------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------------
// PLEASE NOTE THE FOLLOWING ADDITION TO THE LICENSE AGREEMENT:
// If you choose to use this component for generating middleware libraries (with similar
// functionality as dbOvernet, Midas, Asta etc.), those libraries MUST be released as
// Open Source and Freeware!
// -----------------------------------------------------------------------------------
//
// You dont need to state my name in your software, although it would be
// appreciated if you do.
//
// If you find bugs or alter the component (f.ex. see suggested enhancements
// further down), please DONT just send the corrected/new code out on the internet,
// but instead send it to me, so I can put it into the official version. You will
// be acredited if you do so.
//
//
// DISCLAIMER
// By using this component or parts theirof you are accepting the full
// responsibility of the use. You are understanding that the author cant be
// made responsible in any way for any problems occuring using this component.
// You also recognize the author as the creator of this component and agrees
// not to claim otherwize!
//
// Please forward corrected versions (source code ONLY!), comments,
// and emails saying you are using it for this or that project to:
// kbm@components4developers.com
//
// Latest version can be found at:
// http://www.components4developers.com
//=============================================================================
// Remove the remark on the next lines if to keep CSV file compatibility
// between different versions of TkbmMemTable.
//{$define CSV_FILE_1XX_COMPATIBILITY}
//=============================================================================
// History.
// Per v. 3.00, the stream formats will have their own history.
//
// 3.00a alpha
// Initial v. 3.00 CSV stream format release based on the sources of v. 2.53b.
//
// 3.00b alpha 11. Aug. 2001
// Fixed loading CSV with CSVQuote=#0 and CSVRecordDelimiter=#0.
// Fixed not allowing CSVFieldDelimiter=#0.
// Bugs reported by Dave (rave154@yahoo.co.uk)
//
// 3.00c alpha 12. Aug. 2001
// Added support for the Assign method.
//
// 3.00d alpha 20. Sep. 2001
// Changed GetWord to automatically detect and accept unquoted fields.
// Contribution by Georg Zimmer (gzimmer@empoweryourfirm.com).
//
// 3.00e alpha 17. Nov. 2001
// Fixed LoadDef not deciphering the field definition list correctly
// todo with field kind and default expression.
//
// 3.00f beta 30. Jan. 2002
// Fixed bug reading CSV files with blobs.
// Reason was a faulty GetWord algorithm.
//
// 3.00f9 beta 25. Feb. 2002
// Added OnFormatLoadField and OnFormatSaveField event for reformatting of data.
// Added sfQuoteOnlyStrings flag for selecting to only quote string/binary fields during save.
// Published sfNoHeader and completed support for it. It controls if a header should be saved or loaded.
//
// 3.00 Final 14. Jun. 2002
// Changed version status to final.
uses
kbmMemTable,Classes,DB,
{$include kbmMemRes.inc}
SysUtils;
type
TkbmStreamFlagLocalFormat = (sfSaveLocalFormat,sfLoadLocalFormat);
TkbmStreamFlagNoHeader = (sfSaveNoHeader,sfLoadNoHeader);
TkbmStreamFlagQuoteOnlyStrings = (sfSaveQuoteOnlyStrings);
TkbmStreamFlagPlaceholders = (sfSavePlaceholders);
TkbmStreamFlagsLocalFormat = set of TkbmStreamFlagLocalFormat;
TkbmStreamFlagsNoHeader = set of TkbmStreamFlagNoHeader;
TkbmStreamFlagsPlaceHolders = set of TkbmStreamFlagPlaceHolders;
TkbmStreamFlagsQuoteOnlyStrings = set of TkbmStreamFlagQuoteOnlyStrings;
TkbmOnFormatLoadField = procedure(Sender:TObject; Field:TField; var Null:boolean; var Data:string) of object;
TkbmOnFormatSaveField = procedure(Sender:TObject; Field:TField; var Null:boolean; var Data:string) of object;
TkbmCustomCSVStreamFormat = class(TkbmCustomStreamFormat)
private
FDataset:TkbmCustomMemTable;
FOnFormatLoadField:TkbmOnFormatLoadField;
FOnFormatSaveField:TkbmOnFormatSaveField;
Ods,Oms,Ots,Oths:char;
Ocf,Onf:Byte;
Osdf,Ocs:string;
{$IFDEF UNICODE}
buf:TCharArray;
{$ELSE}
buf:PChar;
bufptr:PChar;
{$ENDIF}
remaining_in_buf:integer;
Line,Word:string;
lptr,elptr:PChar;
ProgressCnt:integer;
StreamSize:longint;
FCSVQuote:char;
FCSVFieldDelimiter:char;
FCSVRecordDelimiter:char;
FCSVTrueString,FCSVFalseString:string;
FsfLocalFormat:TkbmStreamFlagsLocalFormat;
FsfNoHeader:TkbmStreamFlagsNoHeader;
FsfPlaceHolders:TkbmStreamFlagsPlaceHolders;
FsfQuoteOnlyStrings:TkbmStreamFlagsQuoteOnlyStrings;
procedure SetCSVFieldDelimiter(Value:char);
protected
FDefLoaded:boolean;
{$IFDEF UNICODE}
FStreamWriter: TStreamWriter;
FStreamReader: TStreamReader;
{$ENDIF}
procedure WriteString(const s: string);
{$IFNDEF UNICODE}
function GetChunk:boolean; virtual;
{$ENDIF}
function GetLine:boolean; virtual;
function GetWord(var null:boolean):string; virtual;
function GetVersion:string; override;
procedure BeforeSave(ADataset:TkbmCustomMemTable); override;
procedure SaveDef(ADataset:TkbmCustomMemTable); override;
procedure SaveData(ADataset:TkbmCustomMemTable); override;
procedure AfterSave(ADataset:TkbmCustomMemTable); override;
procedure DetermineLoadFieldIDs(ADataset:TkbmCustomMemTable; AList:TStringList; Situation:TkbmDetermineLoadFieldsSituation); override;
procedure DetermineLoadFieldIndex(ADataset:TkbmCustomMemTable; ID:string; FieldCount:integer; OrigIndex:integer; var NewIndex:integer; Situation:TkbmDetermineLoadFieldsSituation); override;
procedure BeforeLoad(ADataset:TkbmCustomMemTable); override;
procedure LoadDef(ADataset:TkbmCustomMemTable); override;
procedure LoadData(ADataset:TkbmCustomMemTable); override;
procedure AfterLoad(ADataset:TkbmCustomMemTable); override;
property OnFormatLoadField:TkbmOnFormatLoadField read FOnFormatLoadField write FOnFormatLoadField;
property OnFormatSaveField:TkbmOnFormatSaveField read FOnFormatSaveField write FOnFormatSaveField;
property CSVQuote:char read FCSVQuote write FCSVQuote;
property CSVFieldDelimiter:char read FCSVFieldDelimiter write SetCSVFieldDelimiter;
property CSVRecordDelimiter:char read FCSVRecordDelimiter write FCSVRecordDelimiter;
property CSVTrueString:string read FCSVTrueString write FCSVTrueString;
property CSVFalseString:string read FCSVFalseString write FCSVFalseString;
property sfLocalFormat:TkbmStreamFlagsLocalFormat read FsfLocalFormat write FsfLocalFormat;
property sfNoHeader:TkbmStreamFlagsNoHeader read FsfNoHeader write FsfNoHeader;
property sfPlaceHolders:TkbmStreamFlagsPlaceHolders read FsfPlaceHolders write FsfPlaceHolders;
property sfQuoteOnlyStrings:TkbmStreamFlagsQuoteOnlyStrings read FsfQuoteOnlyStrings write FsfQuoteOnlyStrings;
public
constructor Create(AOwner:TComponent); override;
procedure Assign(Source:TPersistent); override;
end;
TkbmCSVStreamFormat = class(TkbmCustomCSVStreamFormat)
published
property CSVQuote;
property CSVFieldDelimiter;
property CSVRecordDelimiter;
property CSVTrueString;
property CSVFalseString;
property sfLocalFormat;
property sfQuoteOnlyStrings;
property sfNoHeader;
property Version;
property sfData;
property sfCalculated;
property sfLookup;
property sfNonVisible;
property sfBlobs;
property sfDef;
property sfIndexDef;
property sfPlaceHolders;
property sfFiltered;
property sfIgnoreRange;
property sfIgnoreMasterDetail;
property sfDeltas;
property sfDontFilterDeltas;
property sfAppend;
property sfFieldKind;
property sfFromStart;
property OnFormatLoadField;
property OnFormatSaveField;
property OnBeforeLoad;
property OnAfterLoad;
property OnBeforeSave;
property OnAfterSave;
property OnCompress;
property OnDeCompress;
end;
function StringToCodedString(const Source:string):string;
function CodedStringToString(const Source:string):string;
function StringToBase64(const Source:string):string;
function Base64ToString(const Source:string):string;
{$ifdef LEVEL3}
procedure Register;
{$endif}
implementation
const
// Table definition magic words.
kbmTableDefMagicStart = '@@TABLEDEF START@@';
kbmTableDefMagicEnd = '@@TABLEDEF END@@';
// Index definition magic words.
kbmIndexDefMagicStart = '@@INDEXDEF START@@';
kbmIndexDefMagicEnd = '@@INDEXDEF END@@';
// File version magic word.
kbmFileVersionMagic = '@@FILE VERSION@@';
// Current file versions. V. 1.xx file versions are considered 100, 2.xx are considered 2xx etc.
kbmCSVFileVersion = 251;
CSVBUFSIZE=8192;
type
TkbmProtCustomMemTable = class(TkbmCustomMemTable);
TkbmProtCommon = class(TkbmCommon);
{$IFNDEF UNICODE}
function CharInSet(const AChar: Char; const ASet: TSysCharSet): Boolean;
{$IFDEF LEVEL10}inline;{$ENDIF}
begin
Result := AChar in ASet;
end;
{$ENDIF}
// General procedures
// ************************************************************
// Code special characters (LF,CR,%,#0)
// CR (#13) -> %c
// LF (#10) -> %n
// #0 -> %0
// % -> %%
function StringToCodedString(const Source:string):string;
var
i,j:integer;
l:integer;
begin
// Count CR/LF.
l:=0;
for i:=1 to length(Source) do
if CharInSet(Source[i], [#13,#10,'%',#0]) then inc(l);
// If no special characters, return the original string.
if l=0 then
begin
Result:=Source;
exit;
end;
// If any special characters, make room for them.
SetLength(Result,length(Source)+l);
// Code special characters.
j:=1;
for i:=1 to length(Source) do
case Source[i] of
#13: begin
Result[j]:='%'; inc(j);
Result[j]:='c'; inc(j);
end;
#10: begin
Result[j]:='%'; inc(j);
Result[j]:='n'; inc(j);
end;
#0: begin
Result[j]:='%'; inc(j);
Result[j]:='0'; inc(j);
end;
'%': begin
Result[j]:='%'; inc(j);
Result[j]:='%'; inc(j);
end;
else
begin
Result[j]:=Source[i];
inc(j);
end;
end;
end;
// Decode special characters (LF,CR,%,#0)
// %c -> CR (#13)
// %n -> LF (#10)
// %% -> %
// %0 -> #0
function CodedStringToString(const Source:string):string;
var
i,j:integer;
begin
SetLength(Result,length(Source));
// Code special characters.
i:=1;
j:=1;
while true do
begin
if i>length(Source) then break;
if Source[i]='%' then
begin
inc(i);
case Source[i] of
'c': Result[j]:=#13;
'n': Result[j]:=#10;
'%': Result[j]:='%';
'0': Result[j]:=#0;
end;
inc(j);
end
else
begin
Result[j]:=Source[i];
inc(j);
end;
inc(i);
end;
// Cut result string to right length.
if i<>j then SetLength(Result,j-1);
end;
// Code a string as BASE 64.
function StringToBase64(const Source:string):string;
var
Act: Word;
Bits,I,P,Len: Integer;
begin
Bits:=0;
Len:=(Length(Source)*4+2) div 3;
if Len>0 then
begin
SetLength(Result,Len);
P:=1;
Act:=0;
for I:=1 to Pred(Len) do
begin
if Bits<6 then
begin
Act:=(Act shr 6) or (Ord(Source[P]) shl Bits);
Inc(P);
Inc(Bits,2);
end
else
begin
Dec(Bits,6);
Act:=Act shr 6;
end;
Result[I]:=Char(Act and 63+32);
end;
Result[Len]:=Char(Act shr 6+32);
end
else
Result:='';
end;
// Decode BASE64 string.
function Base64ToString(const Source:string): string;
var
Act: Word;
Bits,I,P,Len: Integer;
begin
Len:=(Length(Source)*3) div 4;
SetLength(Result,Len);
Bits:=0;
Act:=0;
P:=1;
for I:=1 to system.Length(Source) do
begin
Act:=Act or (Ord(Source[I])-32) shl Bits;
if Bits>=2 then
begin
Result[P]:=Char(Act and $FF);
Inc(P);
Act:=Act shr 8;
Dec(Bits,2);
end
else
Inc(Bits,6);
end;
end;
// Quote a string.
function QuoteString(const Source:string; Quote:char):string;
begin
if Quote=#0 then Result:=Source
else Result:=AnsiQuotedStr(Source,Quote);
end;
// Extract a quoted string.
function ExtractQuoteString(const Source:string; Quote:char):string;
var
p:PChar;
begin
p:=PChar(Source);
if Quote=#0 then Result:=Source
else Result:=AnsiExtractQuotedStr(p,Quote);
end;
// TKbmCustomCSVStreamFormat
//*******************************************************************
constructor TkbmCustomCSVStreamFormat.Create(AOwner:TComponent);
begin
inherited;
FCSVQuote:='"';
FCSVFieldDelimiter:=',';
FCSVRecordDelimiter:=',';
FCSVTrueString:='True';
FCSVFalseString:='False';
FsfLocalFormat:=[];
FsfPlaceHolders:=[];
end;
function TkbmCustomCSVStreamFormat.GetVersion:string;
begin
Result:='3.00';
end;
procedure TkbmCUstomCSVStreamFormat.Assign(Source:TPersistent);
begin
if Source is TkbmCustomCSVStreamFormat then
begin
CSVQuote:=TkbmCustomCSVStreamFormat(Source).CSVQuote;
CSVFieldDelimiter:=TkbmCustomCSVStreamFormat(Source).CSVFieldDelimiter;
CSVRecordDelimiter:=TkbmCustomCSVStreamFormat(Source).CSVRecordDelimiter;
CSVTrueString:=TkbmCustomCSVStreamFormat(Source).CSVTrueString;
CSVFalseString:=TkbmCustomCSVStreamFormat(Source).CSVFalseString;
sfLocalFormat:=TkbmCustomCSVStreamFormat(Source).sfLocalFormat;
sfPlaceHolders:=TkbmCustomCSVStreamFormat(Source).sfPlaceHolders;
end;
inherited;
end;
procedure TkbmCustomCSVStreamFormat.SetCSVFieldDelimiter(Value:char);
begin
if Value<>#0 then FCSVFieldDelimiter:=Value;
end;
procedure TkbmCustomCSVStreamFormat.WriteString(const s: string);
begin
{$IFDEF UNICODE}
FStreamWriter.Write(s);
{$ELSE}
WorkStream.WriteBuffer(Pointer(s)^, Length(s)*SizeOf(Char));
{$ENDIF}
end;
procedure TkbmCustomCSVStreamFormat.BeforeSave(ADataset:TkbmCustomMemTable);
begin
// Check if trying to save deltas in CSV format. Not supported.
if sfSaveDeltas in sfDeltas then
raise EMemTableError.Create(kbmSavingDeltasBinary);
inherited;
// Setup standard layout for data.
{$IFDEF LEVEL14}
with FormatSettings do
begin
{$ENDIF}
Ods:=DateSeparator;
Oms:=DecimalSeparator;
Ots:=TimeSeparator;
Oths:=ThousandSeparator;
Ocf:=CurrencyFormat;
Onf:=NegCurrFormat;
Osdf:=ShortDateFormat;
Ocs:=CurrencyString;
if not (sfSaveLocalFormat in FsfLocalFormat) then
begin
DateSeparator:='/';
TimeSeparator:=':';
ThousandSeparator:=',';
DecimalSeparator:='.';
ShortDateFormat:='dd/mm/yyyy';
CurrencyString:='';
CurrencyFormat:=0;
NegCurrFormat:=1;
end;
{$IFDEF LEVEL14}
end;
{$ENDIF}
{$IFDEF UNICODE}
if Assigned(FStreamWriter) then
FreeAndNil(FStreamWriter);
FStreamWriter := TStreamWriter.Create(Self.WorkStream, TEncoding.UTF8);
{$ENDIF}
end;
procedure TkbmCustomCSVStreamFormat.AfterSave(ADataset:TkbmCustomMemTable);
begin
// Restore locale setup.
{$IFDEF LEVEL14}
with FormatSettings do
begin
{$ENDIF}
DateSeparator:=Ods;
DecimalSeparator:=Oms;
TimeSeparator:=Ots;
ThousandSeparator:=Oths;
CurrencyFormat:=Ocf;
NegCurrFormat:=Onf;
ShortDateFormat:=Osdf;
CurrencyString:=Ocs;
{$IFDEF LEVEL14}
end;
{$ENDIF}
{$IFDEF UNICODE}
if Assigned(FStreamWriter) then
begin
FStreamWriter.Flush;
FreeAndNil(FStreamWriter);
end;
{$ENDIF}
inherited;
end;
procedure TkbmCustomCSVStreamFormat.SaveDef(ADataset:TkbmCustomMemTable);
var
i:integer;
nf:integer;
s:string;
begin
if not (sfSaveDef in sfDef) then exit;
with TkbmProtCustomMemTable(ADataSet) do
begin
// Setup flags for fields to save.
nf:=Fieldcount;
{$IFNDEF CSV_FILE_1XX_COMPATIBILITY}
// Write file version.
s:=QuoteString(PChar(kbmFileVersionMagic),FCSVQuote)+FCSVFieldDelimiter+QuoteString(IntToStr(kbmCSVFileVersion),FCSVQuote)+#13+#10;
WriteString(s);
{$ENDIF}
// Write header.
s:=QuoteString(PChar(kbmTableDefMagicStart),FCSVQuote)+#13+#10;
WriteString(s);
// Write fielddefinitions.
for i:=0 to nf-1 do
begin
if (SaveFields[i]>=0) or (sfSavePlaceHolders in sfPlaceHolders) then
begin
s:=Fields[i].FieldName+'='+
FieldTypeNames[Fields[i].DataType]+','+
inttostr(Fields[i].Size)+','+
QuoteString(Fields[i].DisplayName,'"')+','+
QuoteString(Fields[i].EditMask,'"')+','+
inttostr(Fields[i].DisplayWidth);
if Fields[i].Required then s:=s+',REQ';
if Fields[i].ReadOnly then s:=s+',RO';
if sfSaveFieldKind in sfFieldKind then
s:=s+','+FieldKindNames[ord(Fields[i].FieldKind)]
else
s:=s+','+FieldKindNames[0];
{$IFDEF LEVEL4}
s:=s+','+QuoteString(Fields[i].DefaultExpression,'"');
{$ENDIF}
s:=QuoteString(PChar(s),FCSVQuote)+#13+#10;
WriteString(s);
end;
end;
{$IFNDEF CSV_FILE_1XX_COMPATIBILITY}
// Check if to write index definitions.
if sfSaveIndexDef in sfIndexDef then
begin
// Write header.
s:=QuoteString(PChar(kbmIndexDefMagicStart),FCSVQuote)+#13+#10;
WriteString(s);
// Write indexdefinitions.
for i:=0 to IndexDefs.count-1 do
with IndexDefs.Items[i] do
begin
s:=Name+'='+
QuoteString(Fields,FCSVQuote)+','+
{$IFDEF LEVEL3}
Name;
{$ELSE}
QuoteString(DisplayName,FCSVQuote);
{$ENDIF}
if ixDescending in Options then s:=s+',DESC';
if ixCaseInsensitive in Options then s:=s+',CASE';
{$IFNDEF LEVEL3}
if ixNonMaintained in Options then s:=s+',NONMT';
{$ENDIF}
if ixUnique in Options then s:=s+',UNIQ';
s:=QuoteString(PChar(s),FCSVQuote)+#13+#10;
WriteString(s);
end;
// Write footer.
s:=QuoteString(PChar(kbmIndexDefMagicEnd),FCSVQuote)+#13+#10;
WriteString(s);
end;
{$ENDIF}
// Write footer.
s:=QuoteString(PChar(kbmTableDefMagicEnd),FCSVQuote)+#13+#10;
WriteString(s);
end;
end;
procedure TkbmCustomCSVStreamFormat.SaveData(ADataset:TkbmCustomMemTable);
var
i,j:integer;
nf:integer;
s,s1,a:string;
Accept:boolean;
null:boolean;
begin
with TkbmProtCustomMemTable(ADataSet) do
begin
FSaveCount:=0;
// Setup flags for fields to save.
nf:=Fieldcount;
// Save header.
if not (sfSaveNoHeader in sfNoHeader) then
begin
// Write all field display names in CSV format.
s:='';
a:='';
for i:=0 to nf-1 do
begin
if (SaveFields[i]>=0) or (sfSavePlaceHolders in sfPlaceHolders) then
begin
s:=s+a+QuoteString({$IFDef VER180}PWideChar{$Else}PChar{$EndIf}(Fields[i].DisplayName),FCSVQuote);
a:=FCSVFieldDelimiter;
end;
end;
if FCSVRecordDelimiter <> #0 then s:=s+FCSVRecordDelimiter;
s:=s+#13+#10;
WriteString(s);
end;
// Write all records in CSV format ordered by current index.
if sfSaveData in sfData then
begin
try
FSavedCompletely:=true;
for j:=0 to CurIndex.References.Count-1 do
begin
// Check if to save more.
if (FSaveLimit>0) and (FSaveCount>=FSaveLimit) then
begin
FSavedCompletely:=false;
break;
end;
// Check if to invoke progress event if any.
if (j mod 100)=0 then Progress(trunc((j/CurIndex.References.count)*100),mtpcSave);
// Setup which record to work on.
OverrideActiveRecordBuffer:=PkbmRecord(CurIndex.References.Items[j]);
if OverrideActiveRecordBuffer=nil then continue;
// Calculate fields.
{$IFDEF LEVEL18}
ClearCalcFields(NativeInt(OverrideActiveRecordBuffer));
GetCalcFields(NativeInt(OverrideActiveRecordBuffer));
{$ELSE}
ClearCalcFields(TRecordBuffer(OverrideActiveRecordBuffer));
GetCalcFields(TRecordBuffer(OverrideActiveRecordBuffer));
{$ENDIF}
// Check filter of record.
Accept:=FilterRecord(OverrideActiveRecordBuffer,false);
if not Accept then continue;
// Check if to accept that record for save.
Accept:=true;
if Assigned(OnSaveRecord) then OnSaveRecord(ADataset,Accept);
if not Accept then continue;
// Write current record.
s:='';
a:='';
for i:=0 to nf-1 do
begin
if SaveFields[i]>=0 then
begin
if Assigned(OnSaveField) then OnSaveField(ADataset,i,Fields[i]);
if (Fields[i].IsNull) then s1:=''
else if Fields[i].DataType in kbmStringTypes then
s1:=StringToCodedString(Fields[i].AsString)
else if Fields[i].DataType in kbmBinaryTypes then
s1:=StringToBase64(Fields[i].AsString)
else if Fields[i].DataType=ftBoolean then
begin
with TBooleanField(Fields[i]) do
if Value then
s1:=FCSVTrueString
else
s1:=FCSVFalseString;
end
else
s1:=Fields[i].AsString;
null:=Fields[i].IsNull;
if assigned(FOnFormatSaveField) then
FOnFormatSaveField(self,Fields[i],null,s1);
if null then
s:=s+a
else if ((sfSaveQuoteOnlyStrings in sfQuoteOnlyStrings) and
(not (Fields[i].DataType in kbmStringTypes+kbmBinaryTypes))) then
s:=s+a+s1
else
s:=s+a+QuoteString(s1,FCSVQuote);
a:=FCSVFieldDelimiter;
end
else if sfSavePlaceHolders in sfPlaceHolders then
begin
s:=s+a;
a:=FCSVFieldDelimiter;
end;
end;
// Add record delimiter.
if FCSVRecordDelimiter <> #0 then s:=s+FCSVRecordDelimiter;
s:=s+#13+#10;
// Write line.
WriteString(s);
// Increment savecounter.
inc(FSaveCount);
end;
finally
OverrideActiveRecordBuffer:=nil;
end;
end;
end;
end;
{$IFNDEF UNICODE}
function TkbmCustomCSVStreamFormat.GetChunk:boolean;
begin
remaining_in_buf:=WorkStream.Read(pointer(buf)^,CSVBUFSIZE);
bufptr:=buf;
Result:=remaining_in_buf>0;
// Show progress.
inc(ProgressCnt);
ProgressCnt:=ProgressCnt mod 100;
if (ProgressCnt=0) then
FDataset.Progress(trunc((WorkStream.Position / StreamSize) * 100),mtpcLoad);
end;
{$ENDIF}
function TkbmCustomCSVStreamFormat.GetLine:boolean;
var
EOF:boolean;
{$IFNDEF UNICODE}
EOL:boolean;
ep,sp:PChar;
TmpStr:string;
{$ENDIF}
begin
{$IFDEF UNICODE}
Line := FStreamReader.ReadLine;
// Show progress.
inc(ProgressCnt);
ProgressCnt:=ProgressCnt mod 100;
if (ProgressCnt=0) then
FDataset.Progress(trunc((WorkStream.Position / StreamSize) * 100),mtpcLoad);
EOF := FStreamReader.EndOfStream;
{$ELSE}
// Cut out a line.
EOL:=false;
EOF:=false;
Line:='';
sp:=bufptr;
ep:=bufptr;
while true do
begin
// Check if need another chunk.
if remaining_in_buf=0 then
begin
// Add to line.
if EOL then
SetString(TmpStr,sp,ep-sp+1)
else
SetString(TmpStr,sp,bufptr-sp);
Line:=Line+TmpStr;
// Check if EOF.
if not GetChunk then
begin
EOF:=true;
break;
end;
sp:=bufptr;
ep:=bufptr-1;
end;
// Check if we got EOL character, skip them and finally break.
if CharInSet(bufptr^, [#0, #10, #13]) then
begin
if not EOL then ep:=bufptr-1;
EOL:=true
end
else if EOL then
begin
SetString(TmpStr,sp,ep-sp+1);
Line:=Line+TmpStr;
break;
end;
// Prepare to look at next char.
Inc(bufptr);
dec(remaining_in_buf);
end;
{$ENDIF}
lptr:=PChar(Line);
elptr:=PChar(Line)+Length(Line);
Result:=(not EOF);
end;
function TkbmCustomCSVStreamFormat.GetWord(var null:boolean):string;
type
tfsmstate=(stStart,stQuote,stText,stDelim);
var
sptr:PChar;
TmpStr:string;
l:integer;
state: tfsmstate;
begin
Result:='';
// Check if parsing without quote.
if FCSVQuote=#0 then
begin
sptr:=lptr;
while (lptr^ <> FCSVFieldDelimiter) and (lptr^ <> FCSVRecordDelimiter) and (lptr<elptr) do inc(lptr);
l:=lptr-sptr;
if (lptr>=elptr) then inc(l); // Allow for missing fieldseperator/recordseperator at end of line.
SetString(Result,sptr,l);
null:=(length(Result)<=0);
if (lptr^=FCSVFieldDelimiter) or (lptr^=FCSVRecordDelimiter) then inc(lptr);
end
else
begin
sptr:=lptr;
state:=stStart;
null:=false;
while state<>stDelim do
begin
if (lptr>=elptr) then exit;
case state of
stStart:
if lptr^=FCSVQuote then
begin
state:=stQuote;
inc(sptr);
end
else if lptr^=FCSVFieldDelimiter then
begin
state:=stDelim;
null:=true;
end
else
state:=stText;
stText:
if lptr^=FCSVFieldDelimiter then
begin
SetString(TmpStr,sptr,lptr-sptr);
sptr:=lptr;
Result:=Result+TmpStr;
state:=stDelim;
end;
stQuote:
if lptr^=FCSVQuote then
begin
// Either got endquote or got double quote.
SetString(TmpStr,sptr,lptr-sptr);
Result:=Result+TmpStr;
inc(lptr);
if lptr^=FCSVQuote then
Result:=Result+FCSVQuote
else
state:=stDelim;
sptr:=lptr;
inc(sptr);
end;
end;
inc(lptr);
end;
end;
end;
{
function TkbmCustomCSVStreamFormat.GetWord(var null:boolean):string;
type
tfsmstate=(stStart,stQuote,stText,stDelim);
var
sptr:PChar;
TmpStr:string;
l:integer;
state: tfsmstate;
begin
Result:='';
// Check if parsing without quote.
if FCSVQuote=#0 then
begin
sptr:=lptr;
while (lptr^ <> FCSVFieldDelimiter) and (lptr^ <> FCSVRecordDelimiter) and (lptr<elptr) do inc(lptr);
l:=lptr-sptr;
if (lptr>=elptr) then inc(l); // Allow for missing fieldseperator/recordseperator at end of line.
SetString(Result,sptr,l);
null:=(length(Result)<=0);
if (lptr^=FCSVFieldDelimiter) or (lptr^=FCSVRecordDelimiter) then inc(lptr);
end
else
begin
sptr:=lptr;
state:=stStart;
null:=false;
while state<>stDelim do
begin
if (lptr>=elptr) then exit;
case state of
stStart:
case lptr^ of
'"': begin
state:=stQuote;
inc(sptr);
end;
',': begin
state:=stDelim;
null:=true;
end;
else
state:=stText;
end;
stText: