forked from csimplestring/delta-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
log_test.go
1126 lines (922 loc) · 30.6 KB
/
log_test.go
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
package deltago
import (
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/barweiss/go-tuple"
"github.com/csimplestring/delta-go/action"
"github.com/csimplestring/delta-go/errno"
"github.com/csimplestring/delta-go/internal/util"
"github.com/csimplestring/delta-go/internal/util/filenames"
"github.com/csimplestring/delta-go/internal/util/path"
"github.com/csimplestring/delta-go/iter"
"github.com/csimplestring/delta-go/op"
"github.com/csimplestring/delta-go/store"
"github.com/csimplestring/delta-go/types"
mapset "github.com/deckarep/golang-set/v2"
"github.com/repeale/fp-go"
"github.com/stretchr/testify/assert"
)
// File log store tests
func getTestFileDir(name string) string {
path, err := filepath.Abs(fmt.Sprintf("./tests/golden/%s/", name))
if err != nil {
panic(err)
}
return "file://" + path + "/"
}
func getTestFileBaseDir() string {
path, err := filepath.Abs("./tests/golden")
if err != nil {
panic(err)
}
return "file://" + path + "/"
}
func getTestFileConfig() Config {
return Config{
StoreType: "file",
}
}
// Azure Blob log store tests
func getTestAzBlobBaseDir() string {
os.Setenv("AZURE_STORAGE_ACCOUNT", "devstoreaccount1")
os.Setenv("AZURE_STORAGE_KEY", "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==")
return "azblob://golden"
}
func getTestAzBlobConfig() Config {
return Config{
StoreType: "azblob",
}
}
// Google Cloud Storage log store tests
func getTestGoogleStorageBaseDir() string {
return "gs://golden"
}
func getTestGoogleStorageConfig() Config {
return Config{
StoreType: "gs",
}
}
// s3 log store tests
func getTestS3BaseDir() string {
return "s3://golden"
}
func getTestS3Config() Config {
return Config{
StoreType: "s3",
}
}
func getTestEngineInfo() string {
return "test-engine-info"
}
func getTestManualUpdate() *op.Operation {
return &op.Operation{Name: op.MANUALUPDATE}
}
func getTestMetedata() *action.Metadata {
st := types.NewStructType([]*types.StructField{types.NewStructField("x", &types.IntegerType{}, true)})
schemaString, err := types.ToJSON(st)
if err != nil {
panic(err)
}
return &action.Metadata{SchemaString: schemaString}
}
type testLogCase struct {
name string
blobDir *util.BlobDir
urlstr string
config Config
dataPathBase string
//
tempFile string
tempDir string
copiedFiles []string
copiedDir string
}
func (t *testLogCase) getLog(name string) (Log, error) {
dataPath := fmt.Sprintf("%s/%s", t.dataPathBase, name)
return ForTable(dataPath, t.config, &SystemClock{})
}
func (t *testLogCase) getTempLog() (Log, error) {
tempDir, tempFile, err := t.blobDir.CreateTemp()
if err != nil {
return nil, err
}
t.tempDir = tempDir
t.tempFile = tempFile
base := strings.TrimSuffix(t.dataPathBase, "/")
dir := strings.TrimSuffix(strings.TrimPrefix(tempDir, "/"), "/")
dataPath := fmt.Sprintf("%s/%s", base, dir)
return ForTable(dataPath, t.config, &SystemClock{})
}
func (t *testLogCase) copyLog(name string) (Log, error) {
dir, files, err := t.blobDir.Copy(name)
if err != nil {
return nil, err
}
t.copiedDir = dir
t.copiedFiles = files
dataPath := fmt.Sprintf("%s/%s", t.dataPathBase, dir)
return ForTable(dataPath, t.config, &SystemClock{})
}
func (t *testLogCase) cleanTempDir() {
if len(t.tempDir) != 0 {
if err := t.blobDir.Delete(t.tempDir, []string{t.tempFile}, true); err != nil {
panic(err)
}
}
if len(t.copiedFiles) != 0 {
if err := t.blobDir.Delete(t.copiedDir, t.copiedFiles, true); err != nil {
panic(err)
}
}
}
func (t *testLogCase) clean() {
if len(t.tempDir) != 0 {
if err := t.blobDir.Delete(t.tempDir, []string{t.tempFile}, true); err != nil {
panic(err)
}
}
if len(t.copiedFiles) != 0 {
if err := t.blobDir.Delete(t.copiedDir, t.copiedFiles, true); err != nil {
panic(err)
}
}
if err := t.blobDir.Close(); err != nil {
panic(err)
}
}
func newTestLogCase(name string, baseDir string, c Config) *testLogCase {
dataPathBase := baseDir
blobURL, err := path.ConvertToBlobURL(baseDir)
if err != nil {
panic(err)
}
blobDir, err := util.NewBlobDir(blobURL)
if err != nil {
panic(err)
}
return &testLogCase{
name: name,
blobDir: blobDir,
urlstr: blobURL,
config: c,
dataPathBase: dataPathBase,
}
}
func newTestLogCases(names ...string) []*testLogCase {
var cases []*testLogCase
for _, name := range names {
if name == "file" {
cases = append(cases, newTestLogCase("file", getTestFileBaseDir(), getTestFileConfig()))
} else if name == "azblob" {
os.Setenv("AZURE_STORAGE_ACCOUNT", "devstoreaccount1")
os.Setenv("AZURE_STORAGE_KEY", "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==")
os.Setenv("AZURE_STORAGE_DOMAIN", "localhost:10000")
os.Setenv("AZURE_STORAGE_PROTOCOL", "http")
os.Setenv("AZURE_STORAGE_IS_CDN", "false")
os.Setenv("AZURE_STORAGE_IS_LOCAL_EMULATOR", "true")
cases = append(cases, newTestLogCase("azblob", getTestAzBlobBaseDir(), getTestAzBlobConfig()))
} else if name == "gs" {
os.Setenv("STORAGE_EMULATOR_HOST", "localhost:4443")
cases = append(cases, newTestLogCase("gs", getTestGoogleStorageBaseDir(), getTestGoogleStorageConfig()))
} else if name == "s3" {
os.Setenv("AWS_ENDPOINT_URL", "http://localhost:4566")
os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
os.Setenv("AWS_DISABLE_SSL", "true")
os.Setenv("AWS_S3_FORCE_PATH_STYLE", "true")
os.Setenv("AWS_ACCESS_KEY_ID", "foo")
os.Setenv("AWS_SECRET_ACCESS_KEY", "bar")
cases = append(cases, newTestLogCase("s3", getTestS3BaseDir(), getTestS3Config()))
} else {
panic("unsupported test case for " + name)
}
}
return cases
}
func TestLog_snapshot(t *testing.T) {
t.Parallel()
getDirDataFiles := func(tablePath string) []string {
tablePath = strings.TrimPrefix(tablePath, "file:")
stats, err := os.ReadDir(tablePath)
assert.NoError(t, err)
var res []string
for _, file := range stats {
if !file.IsDir() && strings.HasSuffix(file.Name(), "snappy.parquet") {
res = append(res, file.Name())
}
}
return res
}
verify := func(s Snapshot, expectedFiles []string, expectedVersion int64) {
files, err := s.AllFiles()
assert.NoError(t, err)
assert.Equal(t, expectedVersion, s.Version())
actual := fp.Map(func(f *action.AddFile) string { return f.Path })(files)
sort.Strings(actual)
sort.Strings(expectedFiles)
assert.Equal(t, expectedFiles, actual)
}
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
table, err := tt.getLog("snapshot-data0")
assert.NoError(t, err)
s, err := table.Snapshot()
assert.NoError(t, err)
data0_files := getDirDataFiles(getTestFileDir("snapshot-data0"))
verify(s, data0_files, 0)
table, err = tt.getLog("snapshot-data1")
assert.NoError(t, err)
s, err = table.Snapshot()
assert.NoError(t, err)
data0_data1_files := getDirDataFiles(getTestFileDir("snapshot-data1"))
verify(s, data0_data1_files, 1)
table, err = tt.getLog("snapshot-data2")
assert.NoError(t, err)
s, err = table.Snapshot()
assert.NoError(t, err)
var data2_files []string
data0_data1_fileset := mapset.NewSet(data0_data1_files...)
// we have overwritten files for data0 & data1; only data2 files should remain
for _, f := range getDirDataFiles(getTestFileDir("snapshot-data2")) {
if !data0_data1_fileset.Contains(f) {
data2_files = append(data2_files, f)
}
}
verify(s, data2_files, 2)
table, err = tt.getLog("snapshot-data3")
assert.NoError(t, err)
s, err = table.Snapshot()
assert.NoError(t, err)
var data2_data3_files []string
for _, f := range getDirDataFiles(getTestFileDir("snapshot-data3")) {
if !data0_data1_fileset.Contains(f) {
data2_data3_files = append(data2_data3_files, f)
}
}
verify(s, data2_data3_files, 3)
table, err = tt.getLog("snapshot-data2-deleted")
assert.NoError(t, err)
s, err = table.Snapshot()
assert.NoError(t, err)
var data3_files []string
data2_fileset := mapset.NewSet(data2_files...)
for _, f := range getDirDataFiles(getTestFileDir("snapshot-data2-deleted")) {
if !data0_data1_fileset.Contains(f) && !data2_fileset.Contains(f) {
data3_files = append(data3_files, f)
}
}
verify(s, data3_files, 4)
table, err = tt.getLog("snapshot-repartitioned")
assert.NoError(t, err)
s, err = table.Snapshot()
assert.NoError(t, err)
allFiles, err := s.AllFiles()
assert.NoError(t, err)
assert.Equal(t, 2, len(allFiles))
assert.Equal(t, int64(5), s.Version())
table, err = tt.getLog("snapshot-vacuumed")
assert.NoError(t, err)
s, err = table.Snapshot()
assert.NoError(t, err)
verify(s, getDirDataFiles(getTestFileDir("snapshot-vacuumed")), 5)
})
}
}
func TestLog_checkpoint(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases(
"file",
"azblob",
"gs",
"s3",
) {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
table, err := tt.getLog("checkpoint")
assert.NoError(t, err)
snapshot, err := table.Snapshot()
assert.NoError(t, err)
assert.NotNil(t, snapshot)
allFiles, err := snapshot.AllFiles()
assert.NoError(t, err)
assert.Equal(t, "15", allFiles[0].Path)
assert.Equal(t, int64(14), snapshot.Version())
scan, err := snapshot.Scan(nil)
assert.NoError(t, err)
assert.NotNil(t, scan)
iter, err := scan.Files()
assert.NoError(t, err)
assert.NotNil(t, iter)
defer iter.Close()
var res []string
var iterErr error
var f *action.AddFile
for f, iterErr = iter.Next(); iterErr == nil; f, iterErr = iter.Next() {
res = append(res, f.Path)
}
assert.ErrorIs(t, iterErr, io.EOF)
iter.Close()
assert.Equal(t, "15", res[0])
})
}
}
func TestLog_updateDeletedDir(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
table, err := tt.copyLog("update-deleted-directory")
assert.NoError(t, err)
err = tt.blobDir.Delete(tt.copiedDir, tt.copiedFiles, true)
assert.NoError(t, err)
s, err := table.Update()
assert.NoError(t, err)
assert.Equal(t, int64(-1), s.Version())
})
}
}
func TestLog_update_should_not_pick_up_delta_files_earlier_than_checkpoint(t *testing.T) {
t.Parallel()
engineInfo := "test-engine-info"
manualUpdate := &op.Operation{Name: op.MANUALUPDATE}
metadata := getTestMetedata()
for _, tt := range newTestLogCases(
"file",
"azblob", "gs", "s3",
) {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
table1, err := tt.getTempLog()
assert.NoError(t, err)
for i := 1; i <= 5; i++ {
txn, err := table1.StartTransaction()
assert.NoError(t, err)
var filesToCommit []action.Action
file := &action.AddFile{Path: fmt.Sprintf("%d", i), PartitionValues: map[string]string{}, Size: 1, ModificationTime: 1, DataChange: true}
if i > 1 {
now := time.Now().UnixMilli()
delete := &action.RemoveFile{Path: fmt.Sprintf("%d", i-1), DeletionTimestamp: &now, DataChange: true}
filesToCommit = append(filesToCommit, delete)
}
filesToCommit = append(filesToCommit, file)
if i == 1 {
err := txn.UpdateMetadata(metadata)
assert.NoError(t, err)
}
_, err = txn.Commit(iter.FromSlice(filesToCommit), manualUpdate, engineInfo)
assert.NoError(t, err)
}
table2, err := ForTable(table1.Path(),
getTestFileConfig(),
&SystemClock{})
assert.NoError(t, err)
for i := 6; i <= 15; i++ {
txn, err := table1.StartTransaction()
assert.NoError(t, err)
file := &action.AddFile{Path: fmt.Sprintf("%d", i), PartitionValues: map[string]string{}, Size: 1, ModificationTime: 1, DataChange: true}
now := time.Now().UnixMilli()
delete := &action.RemoveFile{Path: fmt.Sprintf("%d", i-1), DeletionTimestamp: &now, DataChange: true}
filesToCommit := []action.Action{delete, file}
_, err = txn.Commit(iter.FromSlice(filesToCommit), manualUpdate, engineInfo)
assert.NoError(t, err)
}
// Since log2 is a separate instance, it shouldn't be updated to version 15
s2, err := table2.Snapshot()
assert.NoError(t, err)
assert.Equal(t, int64(4), s2.Version())
updatedS2, err := table2.Update()
assert.NoError(t, err)
s1, err := table1.Snapshot()
assert.NoError(t, err)
assert.Equal(t, s1.Version(), updatedS2.Version(), "Did not update to correct version")
deltas := table2.(*logImpl).snapshotReader.snapshot().logSegment.Deltas
assert.Equal(t, 4, len(deltas), "Expected 4 files starting at version 11 to 14")
versions := fp.Map(func(f *store.FileMeta) int64 { return filenames.DeltaVersion(f.Path()) })(deltas)
sort.Slice(versions, func(i, j int) bool { return versions[i] < versions[j] })
assert.Equal(t, []int64{11, 12, 13, 14}, versions, "Received the wrong files for update")
})
}
}
func TestLog_handle_corrupted_last_checkpoint_file(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
table, err := tt.copyLog("corrupted-last-checkpoint")
assert.NoError(t, err)
logImpl1 := table.(*logImpl)
lc, err := LastCheckpoint(logImpl1.store)
assert.NoError(t, err)
assert.True(t, lc.IsPresent())
lastcheckpoint1 := lc.MustGet()
err = logImpl1.store.Create(logImpl1.logPath + LastCheckpointPath)
assert.NoError(t, err)
table2, err := ForTable(table.Path(),
getTestFileConfig(),
&SystemClock{})
assert.NoError(t, err)
lc2, err := LastCheckpoint(table2.(*logImpl).store)
lastcheckpoint2 := lc2.MustGet()
assert.NoError(t, err)
assert.Equal(t, FromMetadata(*lastcheckpoint2), FromMetadata(*lastcheckpoint1))
})
}
}
func TestLog_paths_should_be_canonicalized_normal_characters(t *testing.T) {
for _, tt := range newTestLogCases("file") {
t.Run(tt.name, func(t *testing.T) {
defer tt.clean()
log, err := tt.getLog("canonicalized-paths-normal-a")
assert.NoError(t, err)
s, err := log.Update()
assert.NoError(t, err)
assert.Equal(t, int64(1), s.Version())
files, err := s.AllFiles()
assert.NoError(t, err)
assert.Equal(t, 0, len(files))
log, err = tt.getLog("canonicalized-paths-normal-b")
assert.NoError(t, err)
s, err = log.Update()
assert.NoError(t, err)
assert.Equal(t, int64(1), s.Version())
files, err = s.AllFiles()
assert.NoError(t, err)
assert.Equal(t, 0, len(files))
})
}
}
func TestLog_paths_should_be_canonicalized_special_characters(t *testing.T) {
for _, tt := range newTestLogCases("file") {
defer tt.clean()
log, err := tt.getLog("canonicalized-paths-special-a")
assert.NoError(t, err)
s, err := log.Update()
assert.NoError(t, err)
assert.Equal(t, int64(1), s.Version())
files, err := s.AllFiles()
assert.NoError(t, err)
assert.Equal(t, 0, len(files))
log, err = tt.getLog("canonicalized-paths-special-b")
assert.NoError(t, err)
s, err = log.Update()
assert.NoError(t, err)
assert.Equal(t, int64(1), s.Version())
files, err = s.AllFiles()
assert.NoError(t, err)
assert.Equal(t, 0, len(files))
}
}
func TestLog_do_not_relative_path_in_remove_files(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
log, err := tt.getTempLog()
assert.NoError(t, err)
path := "schema://" + tt.tempDir + "/a/b/c"
now := time.Now().UnixMilli()
size := int64(0)
metadata := getTestMetedata()
removeFile := &action.RemoveFile{
Path: path,
DeletionTimestamp: &now,
DataChange: true,
ExtendedFileMetadata: false,
PartitionValues: nil,
Size: &size,
Tags: nil,
}
actions := iter.FromSlice([]action.Action{removeFile, metadata})
trx, err := log.StartTransaction()
assert.NoError(t, err)
_, err = trx.Commit(actions, getTestManualUpdate(), getTestEngineInfo())
assert.NoError(t, err)
s, err := log.Update()
assert.NoError(t, err)
commitedRemove, err := s.(*snapshotImp).tombstones()
assert.NoError(t, err)
assert.Equal(t, path, commitedRemove[0].Path)
})
}
}
func TestLog_delete_and_readd_the_same_file_in_different_transactions(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
log, err := tt.getLog("delete-re-add-same-file-different-transactions")
assert.NoError(t, err)
s, err := log.Snapshot()
assert.NoError(t, err)
files, err := s.AllFiles()
assert.NoError(t, err)
assert.Equal(t, 2, len(files))
actualRes := mapset.NewSet(fp.Map(func(a *action.AddFile) string { return a.Path })(files)...)
assert.True(t, actualRes.Equal(mapset.NewSet("foo", "bar")))
foo := fp.Filter(func(af *action.AddFile) bool { return af.Path == "foo" })(files)
assert.Equal(t, int64(1700000000000), foo[0].ModificationTime)
})
}
}
func TestLog_version_not_continuous(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
_, err := tt.getLog("versions-not-contiguous")
assert.ErrorIs(t, err, errno.DeltaVersionNotContinuous([]int64{0, 2}))
})
}
}
func TestLog_state_reconstruction_without_action_should_fail(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
for _, name := range []string{"protocol", "metadata"} {
_, err := tt.getLog(fmt.Sprintf("deltalog-state-reconstruction-without-%s", name))
assert.ErrorIs(t, err, errno.ActionNotFound(name, 0))
}
})
}
}
func TestLog_state_reconstruction_from_checkpoint_with_missing_action_should_fail(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
for _, name := range []string{"protocol", "metadata"} {
_, err := tt.getLog(fmt.Sprintf("deltalog-state-reconstruction-from-checkpoint-missing-%s", name))
assert.ErrorIs(t, err, errno.ActionNotFound(name, 10))
}
})
}
}
func TestLog_table_protocol_version_greater_than_client_reader_protocol_version(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
_, err := tt.getLog("deltalog-invalid-protocol-version")
assert.ErrorIs(t, err, errno.InvalidProtocolVersionError())
})
}
}
func TestLog_get_commit_info(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
log, err := tt.getLog("deltalog-commit-info")
assert.NoError(t, err)
ci, err := log.CommitInfoAt(0)
assert.NoError(t, err)
assert.Equal(t, int64(0), *ci.Version)
assert.Equal(t, int64(1540415658000), ci.Timestamp)
assert.Equal(t, "user_0", *ci.UserID)
assert.Equal(t, "username_0", *ci.UserName)
assert.Equal(t, "WRITE", ci.Operation)
assert.Equal(t, map[string]string{"test": "test"}, ci.OperationParameters)
assert.Equal(t, &action.JobInfo{JobID: "job_id_0", JobName: "job_name_0", RunId: "run_id_0", JobOwnerId: "job_owner_0", TriggerType: "trigger_type_0"}, ci.Job)
assert.Equal(t, &action.NotebookInfo{NotebookId: "notebook_id_0"}, ci.Notebook)
assert.Equal(t, "cluster_id_0", *ci.ClusterId)
assert.Equal(t, int64(-1), *ci.ReadVersion)
assert.Equal(t, "default", *ci.IsolationLevel)
assert.Equal(t, true, *ci.IsBlindAppend)
assert.Equal(t, map[string]string{"test": "test"}, ci.OperationMetrics)
assert.Equal(t, "foo", *ci.UserMetadata)
// use an actual spark transaction example
log, err = tt.getLog("snapshot-vacuumed")
assert.NoError(t, err)
for i := 0; i <= 5; i++ {
ci, err = log.CommitInfoAt(int64(i))
assert.NoError(t, err)
assert.Equal(t, int64(i), *ci.Version)
if i > 0 {
assert.Equal(t, int64(i-1), *ci.ReadVersion)
}
}
_, err = log.CommitInfoAt(99)
assert.Error(t, err)
})
}
}
func TestLog_getChanges_no_data_loss(t *testing.T) {
t.Parallel()
versionToActionsMap := map[int64][]string{
0: {"CommitInfo", "Protocol", "Metadata", "AddFile"},
1: {"CommitInfo", "AddCDCFile", "RemoveFile"},
2: {"CommitInfo", "Protocol", "SetTransaction"},
}
verifyChanges := func(log Log, startVersion int64) {
changes, err := log.Changes(startVersion, false)
assert.NoError(t, err)
versionLogs, err := iter.ToSlice(changes)
assert.NoError(t, err)
assert.Equal(t, 3-startVersion, int64(len(versionLogs)))
var versionsInOrder []int64
for _, versionLog := range versionLogs {
version := versionLog.Version()
actions, err := versionLog.Actions()
assert.NoError(t, err)
actionNames := fp.Map(func(a action.Action) string {
return strings.TrimPrefix(reflect.TypeOf(a).String(), "*action.")
})(actions)
expectedActions := versionToActionsMap[version]
assert.Equal(t, expectedActions, actionNames)
versionsInOrder = append(versionsInOrder, version)
}
j := 0
for i := startVersion; i <= 2; i++ {
assert.Equal(t, int64(i), versionsInOrder[j])
j++
}
}
for _, tt := range newTestLogCases(
"file",
"azblob",
"gs",
"s3",
) {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
log, err := tt.getLog("deltalog-getChanges")
assert.NoError(t, err)
// standard cases
verifyChanges(log, 0)
verifyChanges(log, 1)
verifyChanges(log, 2)
// non-existant start version
versionLogIter, err := log.Changes(3, false)
assert.NoError(t, err)
_, err = versionLogIter.Next()
assert.ErrorIs(t, err, io.EOF)
// negative start version
_, err = log.Changes(-1, false)
assert.ErrorIs(t, err, errno.ErrIllegalArgument)
})
}
}
func TestLog_getChanges_data_loss(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
log, err := tt.copyLog("deltalog-getChanges")
assert.NoError(t, err)
// delete 2 files
err = tt.blobDir.DeleteFile(tt.copiedDir + "/_delta_log/00000000000000000000.json")
assert.NoError(t, err)
err = tt.blobDir.DeleteFile(tt.copiedDir + "/_delta_log/00000000000000000001.json")
assert.NoError(t, err)
vlIter, err := log.Changes(0, false)
assert.NoError(t, err)
versionLogs, err := iter.ToSlice(vlIter)
assert.NoError(t, err)
assert.Equal(t, 1, len(versionLogs))
_, err = log.Changes(0, true)
assert.ErrorIs(t, err, errno.ErrIllegalState)
})
}
}
func TestLog_table_exists(t *testing.T) {
t.Parallel()
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
log, err := tt.getTempLog()
assert.NoError(t, err)
assert.False(t, log.TableExists())
trx, err := log.StartTransaction()
assert.NoError(t, err)
_, err = trx.Commit(iter.FromSlice([]action.Action{
getTestMetedata(),
}), &op.Operation{Name: op.CREATETABLE}, getTestEngineInfo())
assert.NoError(t, err)
assert.True(t, log.TableExists())
})
}
}
func TestLog_schema_must_contain_all_partition_columns(t *testing.T) {
schema := types.NewStructType([]*types.StructField{
types.NewStructField("a", &types.StringType{}, true),
types.NewStructField("b", &types.LongType{}, true),
types.NewStructField("foo", &types.IntegerType{}, true),
types.NewStructField("bar", &types.BooleanType{}, true),
})
schemaString, err := types.ToJSON(schema)
assert.NoError(t, err)
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
inputs := []tuple.T2[[]string, []string]{
tuple.New2([]string{"a", "b"}, []string{}),
tuple.New2([]string{}, []string{}),
tuple.New2([]string{"a", "b", "c", "d"}, []string{"c", "d"}),
}
for _, i := range inputs {
inputPartCols := i.V1
missingPartCols := i.V2
log, err := tt.getTempLog()
assert.NoError(t, err)
metadata := &action.Metadata{
SchemaString: schemaString,
PartitionColumns: inputPartCols,
}
trx, err := log.StartTransaction()
assert.NoError(t, err)
if len(missingPartCols) > 0 {
assert.ErrorIs(t, trx.UpdateMetadata(metadata), errno.ErrDeltaStandalone)
}
// clean up temporary
tt.cleanTempDir()
}
})
}
}
func TestLog_schema_contains_no_data_columns_and_only_partition_columns(t *testing.T) {
for _, tt := range newTestLogCases("file", "azblob", "gs", "s3") {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
defer tt.clean()
log, err := tt.getTempLog()
assert.NoError(t, err)
schema := types.NewStructType([]*types.StructField{
types.NewStructField("part_1", &types.StringType{}, true),
types.NewStructField("part_2", &types.LongType{}, true),
})
schemaString, err := types.ToJSON(schema)
assert.NoError(t, err)
metadata := &action.Metadata{
SchemaString: schemaString,
PartitionColumns: []string{"part_1", "part_2"},
}
trx, err := log.StartTransaction()
assert.NoError(t, err)
assert.ErrorIs(t, trx.UpdateMetadata(metadata), errno.ErrDeltaStandalone)
})
}
}
// func TestLog_getVersionBeforeOrAtTimestamp_and_getVersionAtOrAfterTimestamp(t *testing.T) {
// t.Parallel()
// for _, tt := range newTestLogCases("file", "azblob", "gs") {
// tt := tt
// t.Run(tt.name, func(t *testing.T) {
// t.Parallel()
// defer tt.clean()
// log, err := tt.getTempLog()
// assert.NoError(t, err)
// // ========== case 0: delta table is empty ==========
// v, err := log.VersionBeforeOrAtTimestamp(time.Now().UnixMilli())
// assert.NoError(t, err)
// assert.Equal(t, int64(-1), v)