forked from nao1215/filesql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilesql_test.go
More file actions
4614 lines (3945 loc) · 129 KB
/
filesql_test.go
File metadata and controls
4614 lines (3945 loc) · 129 KB
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 filesql
import (
"bytes"
"compress/gzip"
"context"
"database/sql"
"encoding/csv"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xuri/excelize/v2"
"github.com/apache/arrow/go/v18/arrow"
"github.com/apache/arrow/go/v18/arrow/array"
"github.com/apache/arrow/go/v18/arrow/memory"
)
func TestOpen(t *testing.T) {
t.Parallel()
tests := []struct {
name string
paths []string
wantErr bool
}{
{
name: "Single valid CSV file",
paths: []string{filepath.Join("testdata", "sample.csv")},
wantErr: false,
},
{
name: "Multiple valid files",
paths: []string{filepath.Join("testdata", "sample.csv"), filepath.Join("testdata", "users.csv")},
wantErr: false,
},
{
name: "Directory path",
paths: []string{"testdata"},
wantErr: false,
},
{
name: "Mixed file and directory paths",
paths: []string{filepath.Join("testdata", "sample.csv"), "testdata"},
wantErr: false,
},
{
name: "No paths provided",
paths: []string{},
wantErr: true,
},
{
name: "Non-existent file",
paths: []string{filepath.Join("testdata", "nonexistent.csv")},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Skip slow directory tests in local development
if (tt.name == "Directory path" || tt.name == "Mixed file and directory paths") && os.Getenv("GITHUB_ACTIONS") == "" {
t.Skip("Skipping slow directory test in local development")
}
db, err := Open(tt.paths...)
if tt.wantErr {
assert.Error(t, err, "Open() should have failed")
return
}
assert.NoError(t, err, "Open() should have succeeded")
if !tt.wantErr {
defer db.Close()
// Test that we can query at least one table
if len(tt.paths) > 0 {
// For the sample file test
if strings.Contains(tt.paths[0], "sample.csv") || strings.Contains(tt.paths[0], "testdata") {
rows, err := db.QueryContext(context.Background(), "SELECT COUNT(*) FROM sample")
if err != nil {
assert.Fail(t, "Query() error = %v", err)
return
}
defer rows.Close()
if err := rows.Err(); err != nil {
assert.NoError(t, err, "Rows error")
return
}
var count int
if rows.Next() {
if err := rows.Scan(&count); err != nil {
assert.Fail(t, "Scan() error = %v", err)
return
}
}
if count != 3 {
assert.Fail(t, "Expected 3 rows, got %d", count)
}
}
}
}
})
}
}
func TestSQLQueries(t *testing.T) {
t.Parallel()
db, err := Open(filepath.Join("testdata", "sample.csv"))
require.NoError(t, err, "Failed to open database")
defer db.Close()
tests := []struct {
name string
query string
expected interface{}
}{
{
name: "Count all rows",
query: "SELECT COUNT(*) FROM sample",
expected: 3,
},
{
name: "Select specific user",
query: "SELECT name FROM sample WHERE id = 1",
expected: "John Doe",
},
{
name: "Select with WHERE clause",
query: "SELECT COUNT(*) FROM sample WHERE age > 30",
expected: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rows, err := db.QueryContext(context.Background(), tt.query)
assert.NoError(t, err, "Query() error")
if err != nil {
return
}
defer rows.Close()
assert.NoError(t, rows.Err(), "Rows error")
if rows.Next() {
var result interface{}
if err := rows.Scan(&result); err != nil {
assert.NoError(t, err, "Scan() error")
return
}
switch expected := tt.expected.(type) {
case int:
if count, ok := result.(int64); ok {
assert.Equal(t, expected, int(count), "Expected count to match")
} else {
assert.Failf(t, "Type assertion failed", "Expected int, got %T", result)
}
case string:
if str, ok := result.(string); ok {
assert.Equal(t, expected, str, "Expected string to match")
} else {
assert.Failf(t, "Type assertion failed", "Expected string, got %T", result)
}
}
}
})
}
}
func TestMultipleFiles(t *testing.T) {
t.Parallel()
if os.Getenv("GITHUB_ACTIONS") == "" {
t.Skip("Skipping slow multiple files test in local development")
}
// Test loading multiple files from directory
db, err := Open("testdata")
require.NoError(t, err, "Failed to open directory")
defer db.Close()
tests := []struct {
name string
query string
table string
}{
{
name: "Query sample table",
query: "SELECT COUNT(*) FROM sample",
table: "sample",
},
{
name: "Query users table",
query: "SELECT COUNT(*) FROM users",
table: "users",
},
{
name: "Query products table",
query: "SELECT COUNT(*) FROM products",
table: "products",
},
{
name: "Query logs table",
query: "SELECT COUNT(*) FROM logs",
table: "logs",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rows, err := db.QueryContext(context.Background(), tt.query)
assert.NoError(t, err, "Query() error")
if err != nil {
return
}
defer rows.Close()
assert.NoError(t, rows.Err(), "Rows error")
if rows.Next() {
var count int64
if err := rows.Scan(&count); err != nil {
assert.NoError(t, err, "Scan() error")
return
}
assert.NotEqual(t, int64(0), count, "Expected non-zero count for table %s", tt.table)
}
})
}
}
func TestJoinMultipleTables(t *testing.T) {
t.Parallel()
if os.Getenv("GITHUB_ACTIONS") == "" {
t.Skip("Skipping slow join multiple tables test in local development")
}
// Test joining tables from multiple files
db, err := Open("testdata")
require.NoError(t, err, "Failed to open directory")
defer db.Close()
// Test JOIN query across multiple tables
query := `
SELECT u.name, COUNT(*) as total_tables
FROM users u
CROSS JOIN (SELECT 1) -- Just to demonstrate JOIN capability
WHERE u.id = 1
GROUP BY u.name
`
rows, err := db.QueryContext(context.Background(), query)
if err != nil {
assert.Fail(t, "JOIN Query() error = %v", err)
return
}
defer rows.Close()
if err := rows.Err(); err != nil {
assert.NoError(t, err, "Rows error")
return
}
if rows.Next() {
var name string
var count int64
if err := rows.Scan(&name, &count); err != nil {
assert.Fail(t, "Scan() error = %v", err)
return
}
if name != "Alice" {
assert.Fail(t, "Expected name 'Alice', got '%s'", name)
}
}
}
// TestComplexIntegrationScenarios tests complex combinations of features
func TestComplexIntegrationScenarios(t *testing.T) {
t.Parallel()
t.Run("io.Reader with multiple formats", func(t *testing.T) {
t.Parallel()
// Create CSV data as string
csvData := `id,name,age,salary
1,John Doe,30,50000
2,Jane Smith,25,60000
3,Bob Johnson,35,55000`
// Create TSV data as string
tsvData := `id department budget
1 Engineering 100000
2 Marketing 80000
3 Sales 90000`
// Create LTSV data as string
ltsvData := `id:1 product:Laptop price:1200
id:2 product:Mouse price:25
id:3 product:Keyboard price:75`
// Use NewBuilder with readers
builder := NewBuilder().
AddReader(strings.NewReader(csvData), "employees", FileTypeCSV).
AddReader(strings.NewReader(tsvData), "departments", FileTypeTSV).
AddReader(strings.NewReader(ltsvData), "products", FileTypeLTSV)
validatedBuilder, err := builder.Build(context.Background())
require.NoError(t, err, "Build failed")
db, err := validatedBuilder.Open(context.Background())
require.NoError(t, err, "Open failed")
defer db.Close()
// Test complex JOIN query across all three tables
query := `
SELECT e.name, d.department, p.product, e.salary, p.price
FROM employees e
JOIN departments d ON e.id = d.id
JOIN products p ON e.id = p.id
WHERE e.salary > 40000 AND p.price > 50
ORDER BY e.salary DESC
`
rows, err := db.QueryContext(context.Background(), query)
require.NoError(t, err, "Complex query failed")
defer rows.Close()
var results []struct {
name, dept, product string
salary, price float64
}
for rows.Next() {
var r struct {
name, dept, product string
salary, price float64
}
if err := rows.Scan(&r.name, &r.dept, &r.product, &r.salary, &r.price); err != nil {
require.NoError(t, err, "Scan failed")
}
results = append(results, r)
}
require.NoError(t, rows.Err(), "Rows iteration error")
if len(results) != 2 {
assert.Fail(t, "Expected 2 results, got %d", len(results))
}
})
t.Run("embed.FS integration", func(t *testing.T) {
t.Parallel()
// Create embedded filesystem
testFS := os.DirFS(filepath.Join("testdata", "embed_test"))
builder := NewBuilder().AddFS(testFS)
validatedBuilder, err := builder.Build(context.Background())
require.NoError(t, err, "Build with FS failed")
db, err := validatedBuilder.Open(context.Background())
require.NoError(t, err, "Open with FS failed")
defer db.Close()
// Verify tables from embedded files
tables := []string{"products", "orders", "users"}
for _, table := range tables {
query := "SELECT COUNT(*) FROM " + table // Table name from trusted list
var count int
err := db.QueryRowContext(context.Background(), query).Scan(&count)
if err != nil {
assert.Fail(t, "Failed to query table %s: %v", table, err)
}
if count == 0 {
assert.Fail(t, "Table %s is empty", table)
}
}
// Test cross-table query with embedded data
query := `
SELECT u.name, COUNT(o.order_id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.name
ORDER BY order_count DESC
`
rows, err := db.QueryContext(context.Background(), query)
require.NoError(t, err, "Cross-table query failed")
defer rows.Close()
rowCount := 0
for rows.Next() {
var name string
var orderCount int
if err := rows.Scan(&name, &orderCount); err != nil {
require.NoError(t, err, "Scan failed")
}
rowCount++
}
require.NoError(t, rows.Err(), "Rows iteration error")
if rowCount == 0 {
t.Error("Expected at least one result from cross-table query")
}
})
t.Run("large file streaming with benchmark data", func(t *testing.T) {
t.Parallel()
// Skip this test in local development, only run on GitHub Actions
if os.Getenv("GITHUB_ACTIONS") == "" {
t.Skip("Skipping large file test in local development")
}
builder := NewBuilder().
AddPath(filepath.Join("testdata", "benchmark", "customers100000.csv")).
SetDefaultChunkSize(500) // 500 rows per chunk for testing
validatedBuilder, err := builder.Build(context.Background())
require.NoError(t, err, "Build with large file failed")
db, err := validatedBuilder.Open(context.Background())
require.NoError(t, err, "Open with large file failed")
defer db.Close()
// Test aggregation queries on large dataset
queries := []struct {
name string
query string
}{
{
"Count all rows",
"SELECT COUNT(*) FROM customers100000",
},
{
"Distinct count with GROUP BY",
"SELECT COUNT(DISTINCT `Index`) FROM customers100000",
},
{
"Complex aggregation with window functions",
"SELECT COUNT(*) as total_rows, AVG(CASE WHEN `Index` % 2 = 0 THEN 1.0 ELSE 0.0 END) as even_ratio FROM customers100000",
},
}
for _, q := range queries {
t.Run(q.name, func(t *testing.T) {
start := time.Now()
rows, err := db.QueryContext(context.Background(), q.query)
if err != nil {
require.NoError(t, err, "Query '%s' failed", q.name)
}
defer rows.Close()
hasResults := false
for rows.Next() {
hasResults = true
// Just scan to verify data is accessible
cols, err := rows.Columns()
if err != nil {
require.NoError(t, err, "Failed to get columns")
}
values := make([]interface{}, len(cols))
scanArgs := make([]interface{}, len(cols))
for i := range values {
scanArgs[i] = &values[i]
}
if err := rows.Scan(scanArgs...); err != nil {
require.NoError(t, err, "Scan failed")
}
}
require.NoError(t, rows.Err(), "Rows iteration error")
if !hasResults {
t.Error("Query returned no results")
}
duration := time.Since(start)
t.Logf("Query '%s' took %v", q.name, duration)
})
}
})
t.Run("compressed files handling", func(t *testing.T) {
t.Parallel()
compressedFiles := []string{
filepath.Join("testdata", "sample.csv.gz"),
filepath.Join("testdata", "users.csv.zst"),
filepath.Join("testdata", "logs.ltsv.xz"),
filepath.Join("testdata", "products.tsv.bz2"),
}
builder := NewBuilder().AddPaths(compressedFiles...)
validatedBuilder, err := builder.Build(context.Background())
require.NoError(t, err, "Build with compressed files failed")
db, err := validatedBuilder.Open(context.Background())
require.NoError(t, err, "Open with compressed files failed")
defer db.Close()
// Verify all compressed files were loaded correctly
expectedTables := []string{"sample", "users", "logs", "products"}
for _, table := range expectedTables {
var count int
query := "SELECT COUNT(*) FROM " + table // Table name from trusted list
err := db.QueryRowContext(context.Background(), query).Scan(&count)
if err != nil {
assert.Fail(t, "Failed to query compressed table %s: %v", table, err)
}
if count == 0 {
assert.Fail(t, "Compressed table %s is empty", table)
}
}
// Test complex query across compressed files
query := `
SELECT 'sample' as source, COUNT(*) as count FROM sample
UNION ALL
SELECT 'users' as source, COUNT(*) as count FROM users
UNION ALL
SELECT 'logs' as source, COUNT(*) as count FROM logs
UNION ALL
SELECT 'products' as source, COUNT(*) as count FROM products
ORDER BY count DESC
`
rows, err := db.QueryContext(context.Background(), query)
require.NoError(t, err, "Union query on compressed files failed")
defer rows.Close()
results := make(map[string]int)
for rows.Next() {
var source string
var count int
if err := rows.Scan(&source, &count); err != nil {
require.NoError(t, err, "Scan failed")
}
results[source] = count
}
require.NoError(t, rows.Err(), "Rows iteration error")
if len(results) != 4 {
assert.Fail(t, "Expected 4 tables, got %d", len(results))
}
for table, count := range results {
if count == 0 {
assert.Fail(t, "Table %s has zero rows", table)
}
}
})
t.Run("auto-save functionality", func(t *testing.T) {
t.Parallel()
// Create temporary directory for auto-save test
tempDir := t.TempDir()
// Create builder with auto-save enabled
builder := NewBuilder().
AddPath(filepath.Join("testdata", "sample.csv")).
AddPath(filepath.Join("testdata", "users.csv")).
EnableAutoSave(tempDir, NewDumpOptions().WithFormat(OutputFormatCSV))
validatedBuilder, err := builder.Build(context.Background())
require.NoError(t, err, "Build with auto-save failed")
db, err := validatedBuilder.Open(context.Background())
require.NoError(t, err, "Open with auto-save failed")
// Modify the data
_, err = db.ExecContext(context.Background(), "INSERT INTO sample (id, name, age, email) VALUES (99, 'Test User', 42, 'test@example.com')")
require.NoError(t, err, "INSERT failed")
_, err = db.ExecContext(context.Background(), "UPDATE users SET role = 'super_admin' WHERE name = 'Alice'")
require.NoError(t, err, "UPDATE failed")
// Close to trigger auto-save
if err := db.Close(); err != nil {
assert.NoError(t, err, "Failed to close database")
}
// Verify auto-saved files exist
expectedFiles := []string{"sample.csv", "users.csv"}
for _, filename := range expectedFiles {
filepath := filepath.Join(tempDir, filename)
if _, err := os.Stat(filepath); os.IsNotExist(err) {
assert.Fail(t, "Auto-saved file %s does not exist", filename)
}
}
// Verify the modifications were saved by opening the auto-saved files
newDB, err := Open(tempDir)
require.NoError(t, err, "Failed to open auto-saved files")
defer newDB.Close()
// Check if our modifications are present
var testUser string
err = newDB.QueryRowContext(context.Background(), "SELECT name FROM sample WHERE id = 99").Scan(&testUser)
require.NoError(t, err, "Failed to find inserted test user")
assert.Equal(t, "Test User", testUser, "Expected 'Test User', got '%s'", testUser)
var aliceRole string
err = newDB.QueryRowContext(context.Background(), "SELECT role FROM users WHERE name = 'Alice'").Scan(&aliceRole)
require.NoError(t, err, "Failed to find updated Alice role")
assert.Equal(t, "super_admin", aliceRole, "Expected 'super_admin', got '%s'", aliceRole)
})
t.Run("mixed input sources combination", func(t *testing.T) {
t.Parallel()
// Combine file paths, io.Readers, and embed.FS
csvData := `order_id,customer_name,amount
1001,Alice Johnson,250.00
1002,Bob Smith,175.50`
testFS := os.DirFS(filepath.Join("testdata", "embed_test"))
builder := NewBuilder().
AddPath(filepath.Join("testdata", "sample.csv")). // File path
AddReader(strings.NewReader(csvData), "custom_orders", FileTypeCSV). // io.Reader with unique name
AddFS(testFS). // embed.FS
AddPath(filepath.Join("testdata", "sample2.csv")) // Different file to avoid table name conflict
validatedBuilder, err := builder.Build(context.Background())
require.NoError(t, err, "Build with mixed sources failed")
db, err := validatedBuilder.Open(context.Background())
require.NoError(t, err, "Open with mixed sources failed")
defer db.Close()
// Verify all sources are accessible
tableCounts := map[string]int{}
// Get all table names
rows, err := db.QueryContext(context.Background(), "SELECT name FROM sqlite_master WHERE type='table'")
require.NoError(t, err, "Failed to get table names")
defer rows.Close()
var tableNames []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
require.NoError(t, err, "Scan table name failed")
}
tableNames = append(tableNames, name)
}
require.NoError(t, rows.Err(), "Rows iteration error")
// Count rows in each table
for _, tableName := range tableNames {
var count int
query := fmt.Sprintf("SELECT COUNT(*) FROM `%s`", tableName) //nolint:gosec // Table name from database metadata
err := db.QueryRowContext(context.Background(), query).Scan(&count)
if err != nil {
assert.Fail(t, "Failed to count rows in table %s: %v", tableName, err)
}
tableCounts[tableName] = count
}
// Verify we have expected tables from all sources
expectedTables := []string{"sample", "custom_orders", "sample2"}
for _, expected := range expectedTables {
if count, exists := tableCounts[expected]; !exists {
assert.Fail(t, "Expected table %s not found", expected)
} else if count == 0 {
assert.Fail(t, "Table %s is empty", expected)
}
}
// Test complex query across mixed sources
query := `
SELECT
s.name as sample_name,
o.customer_name as order_customer,
u.name as user_name,
COUNT(*) as match_count
FROM sample s
JOIN custom_orders o ON LOWER(s.name) = LOWER(REPLACE(o.customer_name, ' Johnson', ' Doe'))
JOIN users u ON s.id = u.id
GROUP BY s.name, o.customer_name, u.name
`
rows, err = db.QueryContext(context.Background(), query)
require.NoError(t, err, "Complex mixed-source query failed")
defer rows.Close()
hasResults := false
for rows.Next() {
hasResults = true
var sampleName, orderCustomer, userName string
var matchCount int
if err := rows.Scan(&sampleName, &orderCustomer, &userName, &matchCount); err != nil {
require.NoError(t, err, "Scan complex query failed")
}
// Just verify we can read the data
}
// Note: This query might not return results due to data mismatch, but it should execute without error
require.NoError(t, rows.Err(), "Query execution error")
// Use hasResults to avoid unused variable error
_ = hasResults
})
t.Run("basic database access test", func(t *testing.T) {
t.Parallel()
benchmarkFile := filepath.Join("testdata", "benchmark", "customers100000.csv")
db, err := Open(benchmarkFile)
require.NoError(t, err, "Failed to open benchmark file")
defer db.Close()
// Test basic queries
queries := []struct {
name string
query string
}{
{"count query", "SELECT COUNT(*) FROM customers100000"},
{"limit query", "SELECT `Index` FROM customers100000 LIMIT 5"},
}
for _, tc := range queries {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
rows, err := db.QueryContext(ctx, tc.query)
if err != nil {
require.NoError(t, err, "Query failed")
}
defer rows.Close()
// Process results
for rows.Next() {
cols, err := rows.Columns()
if err != nil {
require.NoError(t, err, "Get columns failed")
}
values := make([]any, len(cols))
scanArgs := make([]any, len(cols))
for k := range values {
scanArgs[k] = &values[k]
}
if err := rows.Scan(scanArgs...); err != nil {
require.NoError(t, err, "Scan failed")
}
}
require.NoError(t, rows.Err(), "Rows error")
})
}
})
}
// TestDumpDatabase tests the DumpDatabase function with various scenarios
func TestDumpDatabase(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
setupFunc func(t *testing.T) *sql.DB
expectError bool
checkFiles []string
}{
{
name: "Single CSV file dump",
setupFunc: func(t *testing.T) *sql.DB {
t.Helper()
db, err := Open(filepath.Join("testdata", "sample.csv"))
require.NoError(t, err, "Failed to open database")
return db
},
expectError: false,
checkFiles: []string{"sample.csv"},
},
{
name: "Multiple files dump",
setupFunc: func(t *testing.T) *sql.DB {
t.Helper()
db, err := Open(filepath.Join("testdata", "sample.csv"), filepath.Join("testdata", "users.csv"))
require.NoError(t, err, "Failed to open database")
return db
},
expectError: false,
checkFiles: []string{"sample.csv", "users.csv"},
},
{
name: "Directory dump",
setupFunc: func(t *testing.T) *sql.DB {
t.Helper()
db, err := Open("testdata")
require.NoError(t, err, "Failed to open database")
return db
},
expectError: false,
checkFiles: []string{"sample.csv", "users.csv", "products.csv", "logs.csv"},
},
{
name: "Modified data dump",
setupFunc: func(t *testing.T) *sql.DB {
t.Helper()
db, err := Open(filepath.Join("testdata", "sample.csv"))
require.NoError(t, err, "Failed to open database")
// Modify data to test persistence
_, err = db.ExecContext(context.Background(), "INSERT INTO sample (id, name, age, email) VALUES (4, 'Test User', 40, 'test@example.com')")
if err != nil {
require.NoError(t, err, "Failed to insert test data")
}
return db
},
expectError: false,
checkFiles: []string{"sample.csv"},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
// Create temporary directory for output
tempDir := t.TempDir()
// Setup database
db := tc.setupFunc(t)
defer db.Close()
// Execute DumpDatabase
err := DumpDatabase(db, tempDir)
// Check error expectation
if (err != nil) != tc.expectError {
assert.Fail(t, "DumpDatabase() error = %v, expectError %v", err, tc.expectError)
return
}
if !tc.expectError {
// Verify expected files were created
for _, fileName := range tc.checkFiles {
filePath := filepath.Join(tempDir, fileName)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
assert.Fail(t, "Expected file %s was not created", fileName)
continue
}
// Read and verify file content
content, err := os.ReadFile(filePath) //nolint:gosec // Safe: filePath is from controlled test data
if err != nil {
assert.Fail(t, "Failed to read dumped file %s: %v", fileName, err)
continue
}
// Basic validation: file should have content and CSV header
if len(content) == 0 {
assert.Fail(t, "Dumped file %s is empty", fileName)
}
contentStr := string(content)
if !strings.Contains(contentStr, "\n") {
assert.Fail(t, "Dumped file %s should contain newlines (header + data)", fileName)
}
// For the modified data test, check if new data is present
if tc.name == "Modified data dump" && fileName == "sample.csv" {
if !strings.Contains(contentStr, "Test User") {
assert.Fail(t, "Modified data not found in dumped file")
}
}
}
}
})
}
}
// TestDumpDatabaseErrors tests error scenarios for DumpDatabase
func TestDumpDatabaseErrors(t *testing.T) {
t.Parallel()
t.Run("Non-filesql connection", func(t *testing.T) {
t.Parallel()
// Create a regular SQLite database (not filesql)
tempDB := filepath.Join(t.TempDir(), "test.db")
db, err := sql.Open("sqlite", tempDB)
if err != nil {
t.Skip("SQLite driver not available, skipping test")
}
defer db.Close()
tempDir := t.TempDir()
// This should return an error since there are no tables in empty database
err = DumpDatabase(db, tempDir)
if err == nil {
t.Error("expected error when calling DumpDatabase on empty database")
}
// Should get "no tables found" error since it's an empty database
expectedErrorMsg := "no tables found in database"
if err.Error() != expectedErrorMsg {
assert.Fail(t, "expected error message '%s', got: %v", expectedErrorMsg, err)
}
})
t.Run("Permission denied output directory", func(t *testing.T) {
t.Parallel()
db, err := Open(filepath.Join("testdata", "sample.csv"))
if err != nil {
require.NoError(t, err, "Failed to open database")
}
defer db.Close()
// Try to write to an invalid directory path that should fail on all platforms
// Use a path that's guaranteed to fail due to invalid characters or permissions
var invalidDir string
if filepath.Separator == '\\' {
// Windows: use invalid characters that are not allowed in directory names
invalidDir = filepath.Join(t.TempDir(), "invalid<>:\"|?*dir")
} else {
// Unix-like: try to write to root directory without permissions
invalidDir = "/root/invalid_permissions_dir"
}
err = DumpDatabase(db, invalidDir)
if err == nil {
t.Error("expected error when writing to invalid directory")
return
}
// Should be a permission or directory creation error
// More flexible error checking since different platforms may return different error messages
errorMsg := err.Error()
hasExpectedError := strings.Contains(errorMsg, "failed to create output directory") ||
strings.Contains(errorMsg, "permission denied") ||
strings.Contains(errorMsg, "access is denied") ||
strings.Contains(errorMsg, "invalid argument") ||
strings.Contains(errorMsg, "cannot create")
if !hasExpectedError {
assert.NoError(t, err, "expected permission or directory creation error, got")
}
})
}
// TestDumpDatabaseCSVFormat tests the CSV format of dumped files
func TestDumpDatabaseCSVFormat(t *testing.T) {
t.Parallel()
db, err := Open(filepath.Join("testdata", "sample.csv"))
if err != nil {
require.NoError(t, err, "Failed to open database")
}
defer db.Close()
tempDir := t.TempDir()
// Dump the database
err = DumpDatabase(db, tempDir)
if err != nil {
require.NoError(t, err, "DumpDatabase() failed")
}
// Read the dumped file
dumpedFile := filepath.Join(tempDir, "sample.csv")
content, err := os.ReadFile(dumpedFile) //nolint:gosec // Safe: dumpedFile is from controlled test output
if err != nil {
require.NoError(t, err, "Failed to read dumped file")
}