-
Notifications
You must be signed in to change notification settings - Fork 5
/
csv-processor.prg
1513 lines (1225 loc) · 43.8 KB
/
csv-processor.prg
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
*!* CSVProcessor
*!* A VFP class to process CSV files
* dependencies
IF _VFP.StartMode = 0
DO LOCFILE("namer.prg")
ELSE
DO namer.prg
ENDIF
* install itself
IF !SYS(16) $ SET("Procedure")
SET PROCEDURE TO (SYS(16)) ADDITIVE
ENDIF
#DEFINE SAFETHIS ASSERT !USED("This") AND TYPE("This") == "O"
#DEFINE MAXCOLUMNS 254
#DEFINE MAXCHARSIZE 254
#DEFINE COLUMNDEFSIZE 18
#DEFINE BOM_UNICODE_16_LE 0hFFFE
#DEFINE BOM_UNICODE_16_BE 0hFEFF
#DEFINE BOM_UTF8 0hEFBBBF
#DEFINE BOM_UTF8_START 0hEFBB
#DEFINE BOM_UTF8_END 0hBF
DEFINE CLASS _CSVProcessor AS Custom
* a name controller to set valid cursor and field names
ADD OBJECT NameController AS Namer
* properties related to the resulting cursor(s)/table(s)
CursorName = ""
* set this property to append to an existing cursor/table
WorkArea = ""
* how to react when table already exists in the database
DropExistingTable = .F.
* Cursor fields / CSV Columns mapping collection
ADD OBJECT FieldMapping AS Collection
* CSV Columns type collection
ADD OBJECT FieldTypes AS Collection
* multiple cursor support
MultipleCursors = .F.
ADD OBJECT MultipleCursorsNames AS Collection
* properties related to how data is stored in the CSV file
* the CSV file has a header row?
HeaderRow = .T.
* number of rows to skip at the beginning of the file
SkipRows = 0
* how rows are delimited
RowSeparator = "" + 0h0d0a
EncodedRowSeparator = ""
* how values are separated
ValueSeparator = ","
* how values are delimited
ValueDelimiter = '"'
* inline newlines may be delimited
InlineDelimitedNewLine = .F.
* how newlines are inserted in a value (.NULL. if newlines are not transformed)
NewLine = .NULL.
* boxed data
BoxedData = .F.
BoxedRowDelimiters = "||"
BoxedSeparator = "-----"
RXBoxedSeparator = "^-+$"
* the decimal point
DecimalPoint = "."
* thousands separator (.NULL. if numbers don't have separators)
ThousandsSeparator = .NULL.
* number unmask before scanning
NumberUnmask = .F.
* Code page translation status while creating columns
CPTrans = .T.
* value for .T. (.NULL., if no logical values)
LogicalTrue = "T"
* value for .F. (.NULL., if no logical values)
LogicalFalse = "F"
* how dates are formatted
DatePattern = "%4Y-%2M-%2D"
* how datetimes are formatted
DateTimePattern = "%4Y-%2M-%2D %2h:%2m:%2s"
* month names, if needed for date anda datetime scanning
MonthNames = "Jan:1:Feb:2:Mar:3:Apr:4:May:5:Jun:6:Jul:7:Aug:8:Sep:9:Oct:10:Nov:11:Dec:12"
* ante- and post-meridian signatures
AnteMeridian = "AM"
PostMeridian = "PM"
* century years
CenturyYears = 0
* Regular expressions pattern alternatives
RXDatePattern = "([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])"
RXDateReformatter = "{^$1-$2-$3}"
RXDateTimePattern = "([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])[ T]([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])"
RXDateTimeReformatter = "{^$1-$2-$3 $4:$5:$6}"
* encoding for binary fields - General, Varbinary, Blob - (hex|base64|plain)
BinaryEncoding = "hex"
* how are .NULL. values represented (can be a string, such as "NULL", or .NULL., in which cases they are replaced by empty values)
NullValue = ""
* also, nullify empty values?
EmptyIsNull = .F.
* trim exported values?
Trimmer = .T.
* trim imported values? (0 = no, 1 = left, 2 = right, 3 = both)
InTrimmer = 0
* sample size, to determine column data types (0 = all rows)
SampleSize = 0
* Regular expression engine
RegExpr = .NULL.
* activate regular expression engine for data types: for now, only D and T are supported
RegularExpressionScanner = ""
* properties related to the file
* file handle
HFile = -1
* UNICODE encoding
UTF = 0
* codepage or locale ID
RegionalID = 0
RegionalIDType = 0
SetCodepage = .F.
* length and position
FileLength = -1
FilePosition = -1
_MemberData = "<VFPData>" + ;
'<memberdata name="antemeridian" type="property" display="AnteMeridian"/>' + ;
'<memberdata name="binaryencoding" type="property" display="BinaryEncoding"/>' + ;
'<memberdata name="boxeddata" type="property" display="BoxedData"/>' + ;
'<memberdata name="boxedrowdelimiters" type="property" display="BoxedRowDelimiters"/>' + ;
'<memberdata name="boxedseparator" type="property" display="BoxedSeparator"/>' + ;
'<memberdata name="cursorname" type="property" display="CursorName"/>' + ;
'<memberdata name="centuryyears" type="property" display="CenturyYears"/>' + ;
'<memberdata name="cptrans" type="property" display="CPTrans"/>' + ;
'<memberdata name="datepattern" type="property" display="DatePattern"/>' + ;
'<memberdata name="datetimepattern" type="property" display="DatetimePattern"/>' + ;
'<memberdata name="decimalpoint" type="property" display="DecimalPoint"/>' + ;
'<memberdata name="dropexistingtable" type="property" display="DropExistingTable"/>' + ;
'<memberdata name="emptyisnull" type="property" display="EmptyIsNull"/>' + ;
'<memberdata name="encodedrowseparator" type="property" display="EncodedRowSeparator"/>' + ;
'<memberdata name="fieldmapping" type="property" display="FieldMapping"/>' + ;
'<memberdata name="filelength" type="property" display="FileLength"/>' + ;
'<memberdata name="fileposition" type="property" display="FilePosition"/>' + ;
'<memberdata name="headerrow" type="property" display="HeaderRow"/>' + ;
'<memberdata name="hfile" type="property" display="HFile"/>' + ;
'<memberdata name="inlinedelimitednewline" type="property" display="InlineDelimitedNewLine"/>' + ;
'<memberdata name="intrimmer" type="property" display="InTrimmer"/>' + ;
'<memberdata name="logicalfalse" type="property" display="LogicalFalse"/>' + ;
'<memberdata name="logicaltrue" type="property" display="LogicalTrue"/>' + ;
'<memberdata name="monthnames" type="property" display="MonthNames"/>' + ;
'<memberdata name="multiplecursors" type="property" display="MultipleCursors"/>' + ;
'<memberdata name="multiplecursorsnames" type="property" display="MultipleCursorsNames"/>' + ;
'<memberdata name="namecontroller" type="property" display="NameController"/>' + ;
'<memberdata name="newline" type="property" display="NewLine"/>' + ;
'<memberdata name="nullvalue" type="property" display="NullValue"/>' + ;
'<memberdata name="numberunmask" type="property" display="NumberUnmask"/>' + ;
'<memberdata name="postmeridian" type="property" display="PostMeridian"/>' + ;
'<memberdata name="regexpr" type="property" display="RegExpr"/>' + ;
'<memberdata name="regionalid" type="property" display="RegionalID"/>' + ;
'<memberdata name="regionalidtype" type="property" display="RegionalIDType"/>' + ;
'<memberdata name="regularexpressionscanner" type="property" display="RegularExpressionScanner"/>' + ;
'<memberdata name="rowseparator" type="property" display="RowSeparator"/>' + ;
'<memberdata name="rxboxedseparator" type="property" display="RXBoxedSeparator"/>' + ;
'<memberdata name="rxdatepattern" type="property" display="RXDatePattern"/>' + ;
'<memberdata name="rxdatereformatter" type="property" display="RXDateReformatter"/>' + ;
'<memberdata name="rxdatetimepattern" type="property" display="RXDateTimePattern"/>' + ;
'<memberdata name="rxdatetimereformatter" type="property" display="RXDateTimeReformatter"/>' + ;
'<memberdata name="samplesize" type="property" display="SampleSize"/>' + ;
'<memberdata name="setcodepage" type="property" display="SetCodepage"/>' + ;
'<memberdata name="skiprows" type="property" display="SkipRows"/>' + ;
'<memberdata name="thousandsseparator" type="property" display="ThousandsSeparator"/>' + ;
'<memberdata name="trimmer" type="property" display="Trimmer"/>' + ;
'<memberdata name="utf" type="property" display="UTF"/>' + ;
'<memberdata name="valuedelimiter" type="property" display="ValueDelimiter"/>' + ;
'<memberdata name="valueseparator" type="property" display="ValueSeparator"/>' + ;
'<memberdata name="workarea" type="property" display="WorkArea"/>' + ;
'<memberdata name="appendtofile" type="method" display="AppendToFile"/>' + ;
'<memberdata name="closefile" type="method" display="CloseFile"/>' + ;
'<memberdata name="createfile" type="method" display="CreateFile"/>' + ;
'<memberdata name="columntype" type="method" display="ColumnType"/>' + ;
'<memberdata name="encodevalue" type="method" display="EncodeValue"/>' + ;
'<memberdata name="getline" type="method" display="GetLine"/>' + ;
'<memberdata name="openfile" type="method" display="OpenFile"/>' + ;
'<memberdata name="processstep" type="method" display="ProcessStep"/>' + ;
'<memberdata name="putline" type="method" display="PutLine"/>' + ;
'<memberdata name="outputdate" type="method" display="OutputDate"/>' + ;
'<memberdata name="outputlogical" type="method" display="OutputLogical"/>' + ;
'<memberdata name="outputnumber" type="method" display="OutputNumber"/>' + ;
'<memberdata name="preencodebinaryvalue" type="method" display="PreEncodeBinaryValue"/>' + ;
'<memberdata name="restoredefaultproperties" type="method" display="RestoreDefaultProperties"/>' + ;
'<memberdata name="scanbinary" type="method" display="ScanBinary"/>' + ;
'<memberdata name="scandate" type="method" display="ScanDate"/>' + ;
'<memberdata name="scanlogical" type="method" display="ScanLogical"/>' + ;
'<memberdata name="scannumber" type="method" display="ScanNumber"/>' + ;
'</VFPData>'
* Init
* attach a VFP name processor to the name controller
PROCEDURE Init
IF EMPTY(This.NameController.AttachProcessor("VFPNamer", "vfp-names.prg"))
RETURN .F. && but fail instantiation if the processor could not be attached
ENDIF
This.NameController.SetProperty("VFPNamer", "AllowReserved", .F.)
This.NameController.SetProperty("VFPNamer", "SafeFieldName", .T.)
This.RegExpr = CREATEOBJECT("VBScript.RegExp") && instantiate a regular expression engine
ENDPROC
* clean up, on exit
PROCEDURE Destroy
This.CloseFile()
ENDPROC
* EncodeValue (Unencoded)
* encode the value, and protect it from ambiguity
FUNCTION EncodeValue (Unencoded AS String) AS String
LOCAL Encoded AS String
* if requested, trim the value
m.Encoded = IIF(This.Trimmer, ALLTRIM(m.Unencoded), m.Unencoded)
* and transform newlines
IF !ISNULL(This.NewLine)
m.Encoded = STRTRAN(m.Encoded, This.RowSeparator, This.NewLine)
ENDIF
* double the delimiters, if present
m.Encoded = STRTRAN(m.Encoded, This.ValueDelimiter, REPLICATE(This.ValueDelimiter, 2))
* if the value includes the separator or end of line, surround the value with the value delimiter
IF This.ValueSeparator $ m.Encoded OR This.RowSeparator $ m.Encoded
m.Encoded = This.ValueDelimiter + m.Encoded + This.ValueDelimiter
ENDIF
RETURN m.Encoded
ENDFUNC
* PreEncodeBinaryValue (Unencoded)
* prepare a Binary value for encoding
FUNCTION PreEncodeBinaryValue (Unencoded AS String) AS String
LOCAL Encoded AS String
DO CASE
CASE This.BinaryEncoding == "hex"
m.Encoded = STRCONV("" + m.Unencoded, 15)
CASE This.BinaryEncoding == "base64"
m.Encoded = STRCONV("" + m.Unencoded, 13)
CASE This.BinaryEncoding == "plain"
m.Encoded = "" + m.Unencoded
OTHERWISE
m.Encoded = m.Unencoded
ENDCASE
RETURN m.Encoded
ENDFUNC
* OpenFile (Filename)
* open a file and set its properties
FUNCTION OpenFile (Filename AS String) AS Boolean
SAFETHIS
ASSERT VARTYPE(m.Filename) == "C" MESSAGE "String parameter expected."
LOCAL BOM AS String
LOCAL TempBuffer AS String
This.CloseFile()
TRY
m.TempBuffer = FILETOSTR(m.Filename)
STRCONV(m.TempBuffer, 9)
CATCH
m.TempBuffer = .NULL.
ENDTRY
This.HFile = FOPEN(m.Filename)
IF This.HFile != -1
* get the file length
This.FileLength = FSEEK(This.HFile, 0, 2)
* and now the encoding (ANSI or some form of UNICODE)
FSEEK(This.HFile, 0, 0)
m.BOM = FREAD(This.HFile, 2)
DO CASE
* UNICODE LE
CASE m.BOM == BOM_UNICODE_16_LE
This.UTF = 1
* UNICODE BE
CASE m.BOM == BOM_UNICODE_16_BE
This.UTF = 2
* UTF-8?
CASE m.BOM == BOM_UTF8_START AND FREAD(This.HFile, 1) == BOM_UTF8_END
This.UTF = 3
* UTF-8 no BOM?
CASE !ISNULL(m.TempBuffer) AND !(LEN(STRCONV(m.TempBuffer, 9)) == LEN(m.TempBuffer)) AND STRCONV(STRCONV(m.TempBuffer, 12), 10) == m.TempBuffer
This.UTF = 4
FSEEK(This.HFile, 0, 0)
* leave the UTF property as it was set
OTHERWISE
FSEEK(This.HFile, 0, 0)
ENDCASE
* prepare an encoded row separator
This._GetRowSeparator(m.TempBuffer)
DO CASE
CASE INLIST(This.UTF, 1, 2) && UNICODE
This.EncodedRowSeparator = STRCONV(This.RowSeparator, 5)
IF This.UTF == 2
This.EncodedRowSeparator = This._SwapEndianess(This.EncodedRowSeparator)
ENDIF
CASE INLIST(This.UTF, 3, 4) && UTF-8
This.EncodedRowSeparator = STRCONV(This.RowSeparator, 9)
OTHERWISE
This.EncodedRowSeparator = This.RowSeparator
ENDCASE
* where the read pointer is
This.FilePosition = FSEEK(This.HFile, 0, 1)
ENDIF
RETURN This.HFile != -1
ENDFUNC
* CreateFile (Filename)
* create a file
FUNCTION CreateFile (Filename AS String) AS Boolean
SAFETHIS
ASSERT VARTYPE(m.Filename) == "C" MESSAGE "String parameter expected."
This.CloseFile()
This.HFile = FCREATE(m.Filename)
IF This.HFile != -1
* prepare a BOM, depending on the UTF property setting
DO CASE
* UNICODE LE
CASE This.UTF = 1
FWRITE(This.HFile, BOM_UNICODE_16_LE)
* UNICODE BE
CASE This.UTF = 2
FWRITE(This.HFile, BOM_UNICODE_16_BE)
* UTF-8?
CASE This.UTF = 3
FWRITE(This.HFile, BOM_UTF8)
* for ANSI or no BOM, just let it be
ENDCASE
ENDIF
RETURN This.HFile != -1
ENDFUNC
* AppendToFile (Filename)
* open a file for appending
FUNCTION AppendToFile (Filename AS String) AS Boolean
SAFETHIS
ASSERT VARTYPE(m.Filename) == "C" MESSAGE "String parameter expected."
LOCAL ARRAY FileExist(1)
IF ADIR(m.FileExist, m.Filename) = 0
RETURN This.CreateFile(m.Filename)
ENDIF
This.CloseFile()
This.HFile = FOPEN(m.Filename, 12)
IF This.HFile != -1 AND FSEEK(This.HFile, 0, 2) = 0
* prepare a BOM, depending on the UTF property setting
DO CASE
* UNICODE LE
CASE This.UTF = 1
FWRITE(This.HFile, BOM_UNICODE_16_LE)
* UNICODE BE
CASE This.UTF = 2
FWRITE(This.HFile, BOM_UNICODE_16_BE)
* UTF-8?
CASE This.UTF = 3
FWRITE(This.HFile, BOM_UTF8)
* for ANSI or no BOM, just let it be
ENDCASE
ENDIF
RETURN This.HFile != -1
ENDFUNC
* GetLine()
* get a line from the CSV file, row separator not included
FUNCTION GetLine () AS String
SAFETHIS
LOCAL FileContents AS String
LOCAL Conversion AS Integer
LOCAL LinePart AS String
LOCAL EndOfLineFound AS Logical
* signal end of file
IF FEOF(This.HFile)
This.FilePosition = This.FileLength
RETURN .NULL.
ENDIF
* get the current position
This.FilePosition = FSEEK(This.HFile, 0, 1)
* read a line from the file stream
m.FileContents = ""
m.EndOfLineFound = .F.
m.LinePart = FREAD(This.HFile, 8192)
DO WHILE ! m.EndOfLineFound
IF RIGHT(m.LinePart, 1) $ This.EncodedRowSeparator AND ! FEOF(This.HFile)
m.LinePart = m.LinePart + FREAD(This.HFile, LEN(This.EncodedRowSeparator))
ENDIF
IF This.EncodedRowSeparator $ m.LinePart
m.LinePart = LEFT(m.LinePart, AT(This.EncodedRowSeparator, m.LinePart) - 1)
m.EndOfLineFound = .T.
ELSE
m.EndOfLineFound = FEOF(This.HFile)
ENDIF
m.FileContents = m.FileContents + m.LinePart
IF ! m.EndOfLineFound
m.LinePart = FREAD(This.HFile, 8192)
ENDIF
ENDDO
This.FilePosition = FSEEK(This.HFile, MIN(This.FilePosition + LEN(m.FileContents) + LEN(This.EncodedRowSeparator), This.FileLength), 0)
* unencode the UNICODE transformation, if needed
DO CASE
CASE This.UTF = 1
* for UNICODE LE, set the conversion
m.Conversion = 6
CASE This.UTF = 2
* for UNICODE BE, swap little and big endians
m.FileContents = This._SwapEndianess(m.FileContents)
* the characters are now little endians, so convert them
m.Conversion = 6
CASE INLIST(This.UTF, 3, 4)
* for UTF-8, use the full string
* but check approximations to quotes in the conversion, first, and protect the result by doubling the result character
IF This.ValueDelimiter == '"'
m.FileContents = STRTRAN(m.FileContents, '”', '""')
ENDIF
m.Conversion = 11
OTHERWISE
m.Conversion = 0
ENDCASE
IF m.Conversion != 0
IF This.RegionalID != 0
m.FileContents = STRCONV(m.FileContents, m.Conversion, This.RegionalID, This.RegionalIDType)
ELSE
m.FileContents = STRCONV(m.FileContents, m.Conversion)
ENDIF
m.FileContents = STRCONV(m.FileContents, 2)
ENDIF
RETURN m.FileContents
ENDFUNC
* GetLineContents()
* get the contents of a logical CSV line (which may spread for several actual lines)
FUNCTION GetLineContents () AS Collection
SAFETHIS
LOCAL Contents AS Collection
LOCAL FileContents AS String
LOCAL ARRAY ColumnsBuffer(1)
LOCAL ColumnText AS String
LOCAL ColLineIndex AS Integer
LOCAL Pending AS String
LOCAL IsDelimited AS Boolean
LOCAL InsideDelimiters AS Boolean
LOCAL TrailDelimiters AS Integer
LOCAL LenDelimiters AS Integer
m.Contents = CREATEOBJECT("Collection")
m.FileContents = This.GetLine()
* get the separator, if it's not set yet
This._GetSeparator(m.FileContents)
* preprocess boxed data
IF This.BoxedData
* ignore line if it is a separator
This.RegExpr.Pattern = This.RXBoxedSeparator
DO WHILE ! ISNULL(m.FileContents)
IF This.RegExpr.Test(m.FileContents)
m.FileContents = This.GetLine()
ELSE
EXIT
ENDIF
ENDDO
* if reached end of file, return an empty line
IF ISNULL(m.FileContents)
RETURN m.Contents
ENDIF
* remove box left and right delimiters
IF ! EMPTY(This.BoxedRowDelimiters)
m.LenDelimiters = LEN(This.BoxedRowDelimiters) / 2
IF LEFT(m.FileContents, m.LenDelimiters) == LEFT(This.BoxedRowDelimiters, m.LenDelimiters)
m.FileContents = SUBSTR(m.FileContents, m.LenDelimiters + 1)
ENDIF
IF RIGHT(m.FileContents, m.LenDelimiters) == RIGHT(This.BoxedRowDelimiters, m.LenDelimiters)
m.FileContents = LEFT(m.FileContents, LEN(m.FileContents) - m.LenDelimiters)
ENDIF
ENDIF
ENDIF
* if a delimiter was set, values can be delimited
m.IsDelimited = LEN(NVL(This.ValueDelimiter, "")) > 0
m.InsideDelimiters = .F.
m.Pending = ""
DO WHILE !ISNULL(m.FileContents)
* get a crude separation
ALINES(m.ColumnsBuffer, m.FileContents, 2, This.ValueSeparator)
m.ColLineIndex = 1
* while there is column to look into
DO WHILE m.ColLineIndex <= ALEN(m.ColumnsBuffer)
* the (partial or complete) value from the CSV field
m.ColumnText = m.ColumnsBuffer(m.ColLineIndex)
* if it includes transformed newlines, change them back into real newlines
IF !ISNULL(This.NewLine)
m.ColumnText = STRTRAN(m.ColumnText, This.NewLine, This.RowSeparator)
ENDIF
* add it to the fetched value
m.Pending = m.Pending + m.ColumnText
* found a delimited field?
IF m.IsDelimited AND LEFT(m.Pending, LEN(This.ValueDelimiter)) == This.ValueDelimiter
m.InsideDelimiters = .T.
m.TrailDelimiters = 0
* check the case where the field may end wth a bunch of delimiters...
IF LEN(m.Pending) > 1
DO WHILE RIGHT(m.ColumnText, LEN(This.ValueDelimiter)) == This.ValueDelimiter
m.TrailDelimiters = m.TrailDelimiters + 1
m.ColumnText = LEFT(m.ColumnText, LEN(m.ColumnText) - LEN(This.ValueDelimiter))
ENDDO
ENDIF
DO CASE
* empty delimited field..
CASE EMPTY(m.ColumnText) AND m.TrailDelimiters = 2
m.Pending = ""
m.InsideDelimiters = .F.
* if the field ended with a delimiter
CASE RIGHT(m.Pending, LEN(This.ValueDelimiter)) == This.ValueDelimiter AND (m.TrailDelimiters / 2) != INT(m.TrailDelimiters / 2)
* remove the delimiters from the column data, at the beginning and at the end of the field
m.Pending = SUBSTR(m.Pending, LEN(This.ValueDelimiter) + 1, LEN(m.Pending) - (LEN(This.ValueDelimiter) + 1))
* and also in the middle
m.Pending = STRTRAN(m.Pending, REPLICATE(This.ValueDelimiter, 2), This.ValueDelimiter)
m.InsideDelimiters = .F.
OTHERWISE
* if not, it was a separator that broke the columns, so add it
IF m.ColLineIndex < ALEN(m.ColumnsBuffer)
m.Pending = m.Pending + This.ValueSeparator
ENDIF
* and continue to fill the current data column from the next CSV column
m.ColLineIndex = m.ColLineIndex + 1
LOOP
ENDCASE
ENDIF
* fetch more columns if the last one was completely fetched...
IF m.ColLineIndex <= ALEN(m.ColumnsBuffer) AND !m.InsideDelimiters
IF BITAND(This.InTrimmer, 0x01) != 0
m.Pending = LTRIM(m.Pending)
ENDIF
IF BITAND(This.InTrimmer, 0x02) != 0
m.Pending = RTRIM(m.Pending)
ENDIF
m.Contents.Add(m.Pending)
m.Pending = ""
ENDIF
m.ColLineIndex = m.ColLineIndex + 1
ENDDO
* if the last column was not completely read, we will try with the next line
IF m.InsideDelimiters
m.Pending = m.Pending + This.RowSeparator
m.FileContents = This.GetLine()
ELSE
EXIT && done, the logical CSV line was completely read
ENDIF
ENDDO
* the contents of each column is stored in the collection items
RETURN m.Contents
ENDFUNC
* PutLine()
* put a line into the CSV file
FUNCTION PutLine (Contents AS String) AS Boolean
SAFETHIS
LOCAL FileContents AS String
LOCAL CharIndex AS Integer
LOCAL TempChar AS Character
* the line ends with a row separator
m.FileContents = m.Contents + This.RowSeparator
* prepare a UNICODE conversion, if necessary
IF This.UTF != 0
m.FileContents = STRCONV(m.FileContents, 1)
ENDIF
DO CASE
* UNICODE 16 bits?
CASE INLIST(This.UTF, 1, 2)
* convert to UNICODE
IF This.RegionalID != 0
m.FileContents = STRCONV(m.FileContents, 5, This.RegionalID, This.RegionalIDType)
ELSE
m.FileContents = STRCONV(m.FileContents, 5)
ENDIF
IF This.UTF = 2 && UNICODE BE? Exchange high order with low order bytes
m.FileContents = This._SwapEndianess(m.FileContents)
ENDIF
* UFT-8?
CASE INLIST(This.UTF, 3, 4)
* convert to UTF-8
IF This.RegionalID != 0
m.FileContents = STRCONV(m.FileContents, 9, This.RegionalID, This.RegionalIDType)
ELSE
m.FileContents = STRCONV(m.FileContents, 9)
ENDIF
ENDCASE
* write the line
RETURN FWRITE(This.HFile, m.FileContents) = LEN(m.FileContents)
ENDFUNC
* CloseFile()
* close the open CSV file
PROCEDURE CloseFile
SAFETHIS
IF This.HFile != -1
FCLOSE(This.HFile)
STORE - 1 TO This.HFile, This.FileLength, This.FilePosition
ENDIF
ENDPROC
* ColumnType (CursornName, ColumnName)
* calculate a field data type
PROTECTED FUNCTION ColumnType (CursorName AS String, ColumnName AS String) AS String
LOCAL ColumnType AS String
LOCAL SampleSize AS Integer
LOCAL NumberValue AS Number
LOCAL ARRAY AdHoc(1)
LOCAL UseRX AS Logical
SELECT (m.CursorName)
* Memo if max length of column is greater than 254
SELECT MAX(LEN(NVL(EVALUATE(m.ColumnName), ""))) FROM (m.CursorName) INTO ARRAY AdHoc
IF m.AdHoc > MAXCHARSIZE
RETURN "M"
ENDIF
* Varchar(10) if all rows are empty or null
IF m.AdHoc = 0
RETURN "V10"
ENDIF
m.SampleSize = This.SampleSize
* if any value is not Datetime
m.ColumnType = "T"
m.UseRX = "T" $ This.RegularExpressionScanner
SCAN FOR !(ISNULL(EVALUATE(m.ColumnName)) OR (ISNULL(This.NullValue) AND EVALUATE(m.ColumnName) == "")) AND m.SampleSize >= 0
IF ISNULL(This.ScanDate(EVALUATE(m.ColumnName), .T., m.UseRX))
* check if Date
m.ColumnType = "D"
EXIT
ENDIF
m.SampleSize = m.SampleSize - IIF(m.SampleSize > 1, 1, IIF(m.SampleSize = 1, 2, 0))
ENDSCAN
IF m.ColumnType == "T"
RETURN m.ColumnType
ENDIF
m.SampleSize = This.SampleSize
m.UseRX = "D" $ This.RegularExpressionScanner
* if any value is not Date
SCAN FOR !(ISNULL(EVALUATE(m.ColumnName)) OR (ISNULL(This.NullValue) AND EVALUATE(m.ColumnName) == "")) AND m.SampleSize >= 0
IF ISNULL(This.ScanDate(EVALUATE(m.ColumnName), .F., m.UseRX))
* check if logical
m.ColumnType = "L"
EXIT
ENDIF
m.SampleSize = m.SampleSize - IIF(m.SampleSize > 1, 1, IIF(m.SampleSize = 1, 2, 0))
ENDSCAN
IF m.ColumnType == "D"
RETURN m.ColumnType
ENDIF
m.SampleSize = This.SampleSize
* if any value is not Logical
SCAN FOR !(ISNULL(EVALUATE(m.ColumnName)) OR (ISNULL(This.NullValue) AND EVALUATE(m.ColumnName) == "")) AND m.SampleSize >= 0
IF ISNULL(This.ScanLogical(EVALUATE(m.ColumnName)))
* check if Integer
m.ColumnType = "I"
EXIT
ENDIF
m.SampleSize = m.SampleSize - IIF(m.SampleSize > 1, 1, IIF(m.SampleSize = 1, 2, 0))
ENDSCAN
IF m.ColumnType == "L"
RETURN m.ColumnType
ENDIF
m.SampleSize = This.SampleSize
* if any value is not Number
SCAN FOR !(ISNULL(EVALUATE(m.ColumnName)) OR (ISNULL(This.NullValue) AND EVALUATE(m.ColumnName) == "")) AND m.SampleSize >= 0
m.NumberValue = This.ScanNumber(EVALUATE(m.ColumnName))
IF ISNULL(m.NumberValue)
* it is a character
m.ColumnType = "V"
EXIT
ENDIF
* but, if Number, check if Integer or Double
IF m.ColumnType == "I" AND (m.NumberValue != INT(m.NumberValue) OR ABS(m.NumberValue) > 2147483647)
m.ColumnType = "B"
ENDIF
m.SampleSize = m.SampleSize - IIF(m.SampleSize > 1, 1, IIF(m.SampleSize = 1, 2, 0))
ENDSCAN
IF m.ColumnType $ "IB"
RETURN m.ColumnType
ENDIF
* every other types failed, get the max length of the character field and set a Varchar() with it
SELECT MAX(LEN(EVALUATE(m.ColumnName))) FROM (m.CursorName) INTO ARRAY AdHoc
RETURN m.ColumnType + LTRIM(STR(m.AdHoc, 3, 0))
ENDFUNC
* ScanNumber (Source)
* scan a string and check if it represents a number
FUNCTION ScanNumber (Source AS String) AS Number
SAFETHIS
ASSERT VARTYPE(m.Source) $ "CX" ;
MESSAGE "String parameter expected."
LOCAL NoThousandsSource AS String
LOCAL CleanSource AS String
LOCAL CleanSource2 AS String
LOCAL Symbols AS String
IF ISNULL(m.Source)
RETURN .NULL.
ENDIF
* remove thousands separators, according to setting
m.NoThousandsSource = IIF(ISNULL(This.ThousandsSeparator), m.Source, CHRTRAN(m.Source, This.ThousandsSeparator, ""))
* unmask to numeric digits, according to setting
IF This.NumberUnmask
m.NoThousandsSource = CHRTRAN(m.NoThousandsSource, CHRTRAN(m.NoThousandsSource, "-0123456789" + This.DecimalPoint, ""), "")
ENDIF
IF TYPE(CHRTRAN(m.NoThousandsSource, This.DecimalPoint, ".")) != "N"
RETURN .NULL.
ENDIF
m.CleanSource = ALLTRIM(m.NoThousandsSource)
m.CleanSource2 = SUBSTR(m.CleanSource, 2)
m.Symbols = CHRTRAN(m.CleanSource, "0123456789+-eE" + This.DecimalPoint, "")
IF LEN(m.Symbols) > 0 OR ;
("-" $ m.CleanSource2 AND ATC("e", m.CleanSource) != AT("-", m.CleanSource2)) OR ;
("+" $ m.CleanSource2 AND ATC("e", m.CleanSource) != AT("+", m.CleanSource2))
RETURN .NULL.
ENDIF
RETURN VAL(CHRTRAN(m.NoThousandsSource, This.DecimalPoint, SET("Point")))
ENDFUNC
* OutputNumber (Source)
* output a number
FUNCTION OutputNumber (Source AS Number) AS String
SAFETHIS
ASSERT VARTYPE(m.Source) $ "NX" ;
MESSAGE "Number parameter expected."
LOCAL Output AS String
LOCAL PostDecimal AS String
LOCAL PreDecimal AS Number
IF ISNULL(m.Source)
RETURN NVL(This.NullValue, "")
ENDIF
m.Output = CHRTRAN(TRANSFORM(m.Source), SET("Point"), This.DecimalPoint)
IF ISNULL(This.ThousandsSeparator) OR ATC("e", m.Output) != 0 OR ABS(m.Source) < 1000
RETURN ALLTRIM(m.Output)
ENDIF
IF This.DecimalPoint $ m.Output
m.PreDecimal = VAL(LEFT(m.Output, AT(This.DecimalPoint, m.Output) - 1))
m.PostDecimal = SUBSTR(m.Output, AT(This.DecimalPoint, m.Output))
ELSE
m.PreDecimal = m.Source
m.PostDecimal = ""
ENDIF
RETURN ALLTRIM(CHRTRAN(TRANSFORM(m.PreDecimal, REPLICATE("###,", 10) + "###"), SET("Separator"), This.ThousandsSeparator)) + m.PostDecimal
ENDFUNC
* ScanLogical (Source)
* scan a string and check if it represents a logical value
FUNCTION ScanLogical (Source AS String) AS Boolean
SAFETHIS
ASSERT VARTYPE(m.Source) $ "CX" ;
MESSAGE "String parameter expected."
DO CASE
CASE ISNULL(m.Source)
RETURN .NULL.
CASE UPPER(m.Source) == This.LogicalFalse
RETURN .F.
CASE UPPER(m.Source) == This.LogicalTrue
RETURN .T.
OTHERWISE
RETURN .NULL.
ENDCASE
ENDFUNC
* OutputLogical (Source)
* output a logical value
FUNCTION OutputLogical (Source AS Boolean) AS String
SAFETHIS
ASSERT VARTYPE(m.Source) $ "LX" ;
MESSAGE "Logical parameter expected."
DO CASE
CASE ISNULL(m.Source)
RETURN NVL(This.NullValue, "")
CASE m.Source
RETURN NVL(This.LogicalTrue, "True")
OTHERWISE
RETURN NVL(This.LogicalFalse, "False")
ENDCASE
ENDFUNC
* ScanDate (Source[, IsTime])
* scan a string and check if it represents a date, against a defined pattern (return .NULL. if no date or datetime, as modelled)
FUNCTION ScanDate (Source AS String, IsTime AS Boolean, UseRegularExpression AS Logical) AS DateOrDatetime
SAFETHIS
ASSERT VARTYPE(m.Source) $ "CX" AND VARTYPE(m.IsTime) == "L" ;
MESSAGE "String and boolean parameters expected."
IF ISNULL(m.Source)
RETURN .NULL.
ENDIF
* the result
LOCAL Result AS DateOrDatetime
* if scanning uses a regular expression
IF m.UseRegularExpression
TRY
* try to get a datetime
IF m.IsTime
This.RegExpr.Pattern = This.RXDateTimePattern
m.Result = EVALUATE(This.RegExpr.Replace(m.Source, This.RXDateTimeReformatter))
IF VARTYPE(m.Result) != "T" OR EMPTY(m.Result)
m.Result = .NULL.
ENDIF
* or a date
ELSE
This.RegExpr.Pattern = This.RXDatePattern
m.Result = EVALUATE(This.RegExpr.Replace(m.Source, This.RXDateReformatter))
IF VARTYPE(m.Result) != "D" OR EMPTY(m.Result)
m.Result = .NULL.
ENDIF
ENDIF
CATCH
m.Result = .NULL.
ENDTRY
RETURN m.Result
ENDIF
* the pattern, as being checked
LOCAL Pattern AS String
LOCAL ChPattern AS Character
* the source, as being scanned
LOCAL Scanned AS String
LOCAL ChSource AS Character
LOCAL ScanPart AS String
* date and time parts
LOCAL IsPart AS Boolean
LOCAL PartYear, PartMonth, PartDay, PartHour, PartMinute, PartSeconds AS Integer
LOCAL PartMeridian AS Boolean
* add hours to 12 Hours format
LOCAL AddHours AS Integer
m.Pattern = IIF(m.IsTime, This.DateTimePattern, This.DatePattern)
STORE - 1 TO m.PartYear, m.PartMonth, m.PartDay, m.PartHour, m.PartMinute, m.PartSeconds
m.PartMeridian = .F.
m.AddHours = 0
m.Scanned = m.Source
* while the pattern has not reached the end
DO WHILE LEN(m.Pattern) > 0
m.ChSource = LEFT(m.Scanned, 1)
m.IsPart = .F.
m.ChPattern = LEFT(m.Pattern, 1)
* found a pattern part
IF m.ChPattern == "%"
* store it, to process next
m.Pattern= SUBSTR(m.Pattern, 2)
m.ChPattern = LEFT(m.Pattern, 1)
m.IsPart = .T.
ENDIF
m.Pattern= SUBSTR(m.Pattern, 2)
DO CASE
* if not a pattern part, source and literal characters in the pattern must match
CASE !m.IsPart
IF !(m.ChSource == m.ChPattern)
RETURN .NULL.
ENDIF
m.Scanned = SUBSTR(m.Scanned, 2)
* %% = %
CASE m.ChPattern == "%"