Repository navigation
Expand file tree
/
Copy pathexample_api_test.go
More file actions
968 lines (825 loc) · 24.1 KB
/
Copy pathexample_api_test.go
File metadata and controls
968 lines (825 loc) · 24.1 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
package filesql_test
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"io"
"log"
"log/slog"
"os"
"path/filepath"
"strings"
"time"
"github.com/nao1215/filesql"
"github.com/nao1215/filesql/dialect"
"github.com/xuri/excelize/v2"
_ "modernc.org/sqlite"
)
func createFilesqlExampleDir(files map[string]string) string {
dir, err := os.MkdirTemp("", "filesql-api-example")
if err != nil {
log.Fatal(err)
}
for name, body := range files {
path := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil {
log.Fatal(err)
}
if err := os.WriteFile(path, []byte(strings.TrimLeft(body, "\n")), 0600); err != nil {
log.Fatal(err)
}
}
return dir
}
// exampleTempDir is a directory of its own for an example to write into, so
// that no example touches a path another program may already be using.
func exampleTempDir() string {
dir, err := os.MkdirTemp("", "filesql-api-example")
if err != nil {
log.Fatal(err)
}
return dir
}
func openExampleSQLiteDB() *sql.DB {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(1)
return db
}
func ExampleLoadInto() {
dir := createFilesqlExampleDir(map[string]string{
"users.csv": `
id,name
1,Alice
2,Bob
`,
})
defer os.RemoveAll(dir)
db := openExampleSQLiteDB()
defer db.Close()
ctx := context.Background()
if _, err := db.ExecContext(ctx, `CREATE TABLE notes (body TEXT)`); err != nil {
log.Fatal(err)
}
if _, err := db.ExecContext(ctx, `INSERT INTO notes VALUES ('kept')`); err != nil {
log.Fatal(err)
}
if err := filesql.LoadInto(ctx, db, filepath.Join(dir, "users.csv")); err != nil {
log.Fatal(err)
}
var users, notes int
if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&users); err != nil {
log.Fatal(err)
}
if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM notes`).Scan(¬es); err != nil {
log.Fatal(err)
}
fmt.Printf("users=%d notes=%d\n", users, notes)
// Output:
// users=2 notes=1
}
func ExampleDBBuilder_SetDefaultChunkSize() {
builder := filesql.NewBuilder().
AddReader(strings.NewReader("id,name\n1,Alice\n2,Bob\n3,Cora\n"), "users", filesql.FileTypeCSV).
SetDefaultChunkSize(2)
db, err := builder.Open(context.Background())
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx := context.Background()
var rows int
if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&rows); err != nil {
log.Fatal(err)
}
fmt.Printf("chunk=2 rows=%d\n", rows)
// Output:
// chunk=2 rows=3
}
func ExampleDBBuilder_WithMalformedRowPolicy() {
csvData := "id,name\n1,Alice\n2\n3,Cora,extra\n4,Dave\n"
builder := filesql.NewBuilder().
AddReader(strings.NewReader(csvData), "users", filesql.FileTypeCSV).
WithMalformedRowPolicy(filesql.MalformedRowSkip)
db, err := builder.Open(context.Background())
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx := context.Background()
var rows int
if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&rows); err != nil {
log.Fatal(err)
}
fmt.Printf("loaded rows=%d\n", rows)
// Output:
// loaded rows=2
}
func ExampleDBBuilder_WithDialect() {
builder := filesql.NewBuilder().
AddReader(strings.NewReader("id,shipped_at\n1,2024-12-31 09:07:00\n"), "orders", filesql.FileTypeCSV).
WithDialect(dialect.MySQL)
db, err := builder.Open(context.Background())
if err != nil {
log.Fatal(err)
}
defer db.Close()
// MySQL syntax: DATE_FORMAT with the 24-hour time and the ISO week its
// year belongs to.
var shipped string
if err := db.QueryRowContext(context.Background(),
`SELECT DATE_FORMAT(shipped_at, '%T on week %v of %x') FROM orders`).Scan(&shipped); err != nil {
log.Fatal(err)
}
fmt.Println(shipped)
// Output:
// 09:07:00 on week 01 of 2025
}
func ExampleDBBuilder_WithLogger() {
ctx := context.Background()
// A *slog.Logger is what the builder takes, so where the records go and
// which levels are kept are the handler's business. This one drops the
// timestamp so the example's output is stable.
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{
Level: slog.LevelInfo,
ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
if attr.Key == slog.TimeKey {
return slog.Attr{}
}
return attr
},
}))
builder := filesql.NewBuilder().
WithLogger(logger).
AddReader(strings.NewReader("id,name\n1,Alice\n"), "users", filesql.FileTypeCSV)
db, err := builder.Open(ctx)
if err != nil {
log.Fatal(err)
}
defer db.Close()
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
fmt.Println(lines[0])
fmt.Println(lines[len(lines)-1])
// Output:
// level=INFO msg="build completed" collected_paths=0 readers=1
// level=INFO msg="database opened successfully"
}
func ExampleDBBuilder_OpenReadOnly() {
ctx := context.Background()
builder := filesql.NewBuilder().
AddReader(strings.NewReader("id,name\n1,Alice\n2,Bob\n"), "users", filesql.FileTypeCSV)
// The result is an ordinary *sql.DB whose connections carry SQLite's
// query_only pragma, so a write is refused by the engine rather than by
// this package.
db, err := builder.OpenReadOnly(ctx)
if err != nil {
log.Fatal(err)
}
defer db.Close()
var rows int
if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&rows); err != nil {
log.Fatal(err)
}
_, err = db.ExecContext(ctx, `INSERT INTO users VALUES (3, 'Cora')`)
fmt.Printf("rows=%d write_blocked=%t\n", rows, err != nil)
// Output:
// rows=2 write_blocked=true
}
func ExampleDBBuilder_LoadInto() {
db := openExampleSQLiteDB()
defer db.Close()
ctx := context.Background()
if _, err := db.ExecContext(ctx, `CREATE TABLE notes (body TEXT)`); err != nil {
log.Fatal(err)
}
if _, err := db.ExecContext(ctx, `INSERT INTO notes VALUES ('ready')`); err != nil {
log.Fatal(err)
}
builder := filesql.NewBuilder().
AddReader(strings.NewReader("id,name\n1,Alice\n2,Bob\n"), "users", filesql.FileTypeCSV)
if err := builder.LoadInto(ctx, db); err != nil {
log.Fatal(err)
}
var users, notes int
if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&users); err != nil {
log.Fatal(err)
}
if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM notes`).Scan(¬es); err != nil {
log.Fatal(err)
}
fmt.Printf("users=%d notes=%d\n", users, notes)
// Output:
// users=2 notes=1
}
func ExampleDBBuilder_LoadIntoTx() {
db := openExampleSQLiteDB()
defer db.Close()
ctx := context.Background()
builder := filesql.NewBuilder().
AddReader(strings.NewReader("id,name\n1,Alice\n2,Bob\n"), "users", filesql.FileTypeCSV)
// The caller owns the transaction: the load lands only on Commit, and a
// Rollback discards it.
tx, err := db.BeginTx(ctx, nil)
if err != nil {
log.Fatal(err)
}
if err := builder.LoadIntoTx(ctx, tx); err != nil {
log.Fatal(err)
}
if err := tx.Commit(); err != nil {
log.Fatal(err)
}
var users int
if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&users); err != nil {
log.Fatal(err)
}
fmt.Printf("users=%d\n", users)
// Output:
// users=2
}
func ExampleCompressionType_NewWriter() {
var compressed bytes.Buffer
writer, err := filesql.CompressionGZ.NewWriter(&compressed)
if err != nil {
log.Fatal(err)
}
if _, err := io.WriteString(writer, "hello"); err != nil {
log.Fatal(err)
}
// Closing finalizes the compressed stream. It does not close the
// destination, which is still the caller's.
if err := writer.Close(); err != nil {
log.Fatal(err)
}
fmt.Println(compressed.Len() > 0)
// Output:
// true
}
func ExampleCompressionType_NewReader() {
var compressed bytes.Buffer
writer, err := filesql.CompressionGZ.NewWriter(&compressed)
if err != nil {
log.Fatal(err)
}
if _, err := io.WriteString(writer, "id,total\n1,980\n"); err != nil {
log.Fatal(err)
}
if err := writer.Close(); err != nil {
log.Fatal(err)
}
// The codec is named rather than guessed, which is what a caller who
// already knows it does; OpenReader takes it from a path instead.
reader, err := filesql.CompressionGZ.NewReader(bytes.NewReader(compressed.Bytes()))
if err != nil {
log.Fatal(err)
}
defer reader.Close()
plain, err := io.ReadAll(reader)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(plain))
// Output:
// id,total
// 1,980
}
func ExampleWithCompression() {
var compressed bytes.Buffer
writer, err := filesql.CompressionGZ.NewWriter(&compressed)
if err != nil {
log.Fatal(err)
}
if _, err := io.WriteString(writer, "id,total\n1,980\n2,1200\n"); err != nil {
log.Fatal(err)
}
if err := writer.Close(); err != nil {
log.Fatal(err)
}
// A reader carries no file name, so the codec wrapping it is declared.
// A path does carry one, and AddPath reads the codec from it.
ctx := context.Background()
db, err := filesql.NewBuilder().
AddReader(bytes.NewReader(compressed.Bytes()), "orders", filesql.FileTypeCSV,
filesql.WithCompression(filesql.CompressionGZ)).
Open(ctx)
if err != nil {
log.Fatal(err)
}
defer db.Close()
var total int
if err := db.QueryRowContext(ctx, `SELECT SUM(total) FROM orders`).Scan(&total); err != nil {
log.Fatal(err)
}
fmt.Println(total)
// Output:
// 2180
}
func ExampleOpenReader() {
dir := createFilesqlExampleDir(map[string]string{
"orders.csv": `
id,total
1,980
`,
})
defer os.RemoveAll(dir)
reader, err := filesql.OpenReader(filepath.Join(dir, "orders.csv"))
if err != nil {
log.Fatal(err)
}
defer func() {
if err := reader.Close(); err != nil {
log.Fatal(err)
}
}()
body, err := io.ReadAll(reader)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(body))
// Output:
// id,total
// 1,980
}
func ExampleRemoveCompressionExtension() {
fmt.Println(filesql.RemoveCompressionExtension("orders.csv.gz"))
// Output:
// orders.csv
}
func ExampleNewDumpOptions() {
opts := filesql.NewDumpOptions()
fmt.Printf("%s %q\n", opts.Format, opts.FileExtension())
// Output:
// csv ".csv"
}
func ExampleDumpOptions_WithFormat() {
opts := filesql.NewDumpOptions().WithFormat(filesql.OutputFormatTSV)
fmt.Println(opts.FileExtension())
// Output:
// .tsv
}
func ExampleDumpOptions_WithCompression() {
opts := filesql.NewDumpOptions().WithCompression(filesql.CompressionGZ)
fmt.Println(opts.FileExtension())
// Output:
// .csv.gz
}
func ExampleDumpOptions_WithEncoding() {
// Output is UTF-8 unless asked otherwise. A value the encoding cannot write
// fails the save rather than being replaced.
opts := filesql.NewDumpOptions().WithEncoding(filesql.EncodingShiftJIS)
fmt.Println(opts.Encoding)
// Output:
// shift-jis
}
func ExampleDumpOptions_WithLineEnding() {
// Output ends its records with "\n" unless asked otherwise. A save that
// overwrites a file it loaded from a path keeps that file's own terminator
// without being told.
opts := filesql.NewDumpOptions().WithLineEnding(filesql.LineEndingCRLF)
fmt.Println(opts.LineEnding)
// Output:
// crlf
}
func ExampleOutputFormat_Extension() {
fmt.Println(filesql.OutputFormatParquet.Extension())
// Output:
// .parquet
}
func ExampleCompressionType_Extension() {
fmt.Println(filesql.CompressionXZ.Extension())
// Output:
// .xz
}
func ExampleMalformedRowPolicy_String() {
fmt.Println(filesql.MalformedRowStop)
fmt.Println(filesql.MalformedRowSkip)
fmt.Println(filesql.MalformedRowFill)
// Output:
// stop
// skip
// fill
}
func ExampleExcelSheetPolicy_String() {
fmt.Println(filesql.ExcelSheetPolicyAll)
fmt.Println(filesql.ExcelSheetPolicyVisibleOnly)
// Output:
// all
// visible-only
}
func ExampleParseError() {
dir := createFilesqlExampleDir(map[string]string{
"users.csv": "id,name\n1,alice\n",
"orders.csv": "id,total\n1,980,extra\n",
})
defer os.RemoveAll(dir)
_, err := filesql.Open(context.Background(),
filepath.Join(dir, "users.csv"), filepath.Join(dir, "orders.csv"))
if err == nil {
log.Fatal("the second file should have failed to load")
}
// A load of several inputs says which one failed, and the cause is
// reachable on its own for a caller that has already named the file.
var parseErr *filesql.ParseError
if !errors.As(err, &parseErr) {
log.Fatalf("want a *filesql.ParseError, got %T", err)
}
fmt.Println(filepath.Base(parseErr.Source))
fmt.Println(errors.Is(err, filesql.ErrParsing))
fmt.Println(errors.Is(err, filesql.ErrColumnMismatch))
// Output:
// orders.csv
// true
// true
}
// exampleWorkbook writes a workbook holding one shown sheet and one hidden
// sheet, and returns its path.
func exampleWorkbook(dir string) string {
f := excelize.NewFile()
defer func() { _ = f.Close() }()
for _, sheet := range []string{"Sales", "Scratch"} {
if sheet != "Sheet1" {
if _, err := f.NewSheet(sheet); err != nil {
log.Fatal(err)
}
}
if err := f.SetCellValue(sheet, "A1", "region"); err != nil {
log.Fatal(err)
}
if err := f.SetCellValue(sheet, "A2", sheet); err != nil {
log.Fatal(err)
}
}
if err := f.DeleteSheet("Sheet1"); err != nil {
log.Fatal(err)
}
if err := f.SetSheetVisible("Scratch", false); err != nil {
log.Fatal(err)
}
path := filepath.Join(dir, "book.xlsx")
if err := f.SaveAs(path); err != nil {
log.Fatal(err)
}
return path
}
func ExampleDBBuilder_WithExcelSheetPolicy() {
dir := exampleTempDir()
defer os.RemoveAll(dir)
path := exampleWorkbook(dir)
builder := filesql.NewBuilder().
AddPath(path).
WithExcelSheetPolicy(filesql.ExcelSheetPolicyVisibleOnly)
db, err := builder.Open(context.Background())
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.QueryContext(context.Background(),
`SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
log.Fatal(err)
}
fmt.Println(name)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
// Output:
// book_Sales
}
func ExampleExcelSheetsInFile() {
dir := exampleTempDir()
defer os.RemoveAll(dir)
path := exampleWorkbook(dir)
sheets, err := filesql.ExcelSheetsInFile(path)
if err != nil {
log.Fatal(err)
}
for _, sheet := range sheets {
fmt.Printf("%s visible=%t\n", sheet.Name, sheet.Visible)
}
// Output:
// Sales visible=true
// Scratch visible=false
}
// ExampleLoadInto_dumpDatabase completes the cycle a caller-managed database is
// for: load files into a database you already own, query across what was there
// and what arrived, then write the result back out.
func ExampleLoadInto_dumpDatabase() {
dir := createFilesqlExampleDir(map[string]string{
"users.csv": `
id,name
1,Alice
2,Bob
`,
})
defer os.RemoveAll(dir)
// openExampleSQLiteDB pins the pool to one connection, which SQLite's
// ":memory:" requires: the database is private per connection, so a second
// connection would not see the loaded tables.
db := openExampleSQLiteDB()
defer db.Close()
ctx := context.Background()
if err := filesql.LoadInto(ctx, db, filepath.Join(dir, "users.csv")); err != nil {
log.Fatal(err)
}
if _, err := db.ExecContext(ctx, `UPDATE users SET name = 'Carol' WHERE id = 2`); err != nil {
log.Fatal(err)
}
out := filepath.Join(dir, "out")
if err := filesql.DumpDatabase(context.Background(), db, out); err != nil {
log.Fatal(err)
}
saved, err := os.ReadFile(filepath.Join(out, "users.csv")) //nolint:gosec // path built from this example's own temp directory
if err != nil {
log.Fatal(err)
}
fmt.Print(string(saved))
// Output:
// id,name
// 1,Alice
// 2,Carol
}
// ExampleExcelSheetsInReader is ExampleExcelSheetsInFile for a workbook that
// arrived as bytes rather than as a file.
func ExampleExcelSheetsInReader() {
dir := exampleTempDir()
defer os.RemoveAll(dir)
path := exampleWorkbook(dir)
// A workbook a caller holds in memory, downloaded or embedded rather than
// read from disk. The reader must yield the workbook itself: a codec around
// it has no name to be detected from.
body, err := os.ReadFile(path) //nolint:gosec // path built by this example
if err != nil {
log.Fatal(err)
}
sheets, err := filesql.ExcelSheetsInReader(bytes.NewReader(body))
if err != nil {
log.Fatal(err)
}
for _, sheet := range sheets {
fmt.Printf("%s visible=%t\n", sheet.Name, sheet.Visible)
}
// Output:
// Sales visible=true
// Scratch visible=false
}
func ExampleExcelSheetTableNames() {
tables, err := filesql.ExcelSheetTableNames("book.xlsx", []string{"Sales", "Q1 sales"})
if err != nil {
log.Fatal(err)
}
fmt.Println(tables)
// "Q1 sales" and "Q1.sales" both sanitize to one identifier, so the second
// sheet loaded would replace the first with nothing said about it. Asking
// first is how a caller refuses the workbook before loading any of it.
_, err = filesql.ExcelSheetTableNames("book.xlsx", []string{"Q1 sales", "Q1.sales"})
fmt.Println(errors.Is(err, filesql.ErrDuplicateTable))
// Output:
// [book_Sales book_Q1_sales]
// true
}
// ExampleDBBuilder_SkippedRows shows what MalformedRowSkip discarded. The
// policy is an instruction from the caller, but one dropped row and most of the
// file dropped look alike without the counts.
func ExampleDBBuilder_SkippedRows() {
csvData := "id,name\n1,Alice\n2\n3,Cora,extra\n4,Dave\n"
builder := filesql.NewBuilder().
AddReader(strings.NewReader(csvData), "users", filesql.FileTypeCSV).
WithMalformedRowPolicy(filesql.MalformedRowSkip)
db, err := builder.Open(context.Background())
if err != nil {
log.Fatal(err)
}
defer db.Close()
for _, skipped := range builder.SkippedRows() {
fmt.Printf("%s: %d of %d rows skipped\n", skipped.Table, skipped.Count, skipped.Total)
}
// Output:
// users: 2 of 4 rows skipped
}
func ExampleFileType_String() {
fmt.Println(filesql.FileTypeCSV, filesql.FileTypeLTSV, filesql.FileTypeParquet)
// Output: CSV LTSV Parquet
}
func ExampleCompressionType_String() {
fmt.Println(filesql.CompressionNone, filesql.CompressionGZ, filesql.CompressionZSTD)
// Output: none gz zstd
}
func ExampleEncoding_String() {
fmt.Println(filesql.EncodingUTF8, filesql.EncodingShiftJIS, filesql.EncodingEUCJP)
// Output: utf-8 shift-jis euc-jp
}
func ExampleLineEnding_String() {
fmt.Println(filesql.LineEndingLF, filesql.LineEndingCRLF)
// Output: lf crlf
}
func ExampleOutputFormat_String() {
fmt.Println(filesql.OutputFormatCSV, filesql.OutputFormatTSV, filesql.OutputFormatXLSX)
// Output: csv tsv xlsx
}
// ExampleDumpACH loads an ACH file, edits one entry, and writes the file back.
//
// The write rebuilds the file from the source it was loaded from, so that file
// must still be readable. Control records are derived rather than stored: an
// edited amount is balanced by the write, and an edit to a control column is
// overwritten by the recalculation.
func ExampleDumpACH() {
dir := exampleTempDir()
defer os.RemoveAll(dir)
ctx := context.Background()
db, err := filesql.Open(context.Background(), "testdata/ppd-debit.ach")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.ExecContext(ctx,
`UPDATE ppd_debit_entries SET individual_name = 'Alice Smith'`); err != nil {
log.Fatal(err)
}
out := filepath.Join(dir, "edited.ach")
if err := filesql.DumpACH(ctx, db, "ppd_debit", out); err != nil {
log.Fatal(err)
}
reloaded, err := filesql.Open(context.Background(), out)
if err != nil {
log.Fatal(err)
}
defer reloaded.Close()
var name string
var amount int64
if err := reloaded.QueryRowContext(ctx,
`SELECT individual_name, amount FROM edited_entries`).Scan(&name, &amount); err != nil {
log.Fatal(err)
}
fmt.Printf("%s %d\n", name, amount)
// Output:
// Alice Smith 100000000
}
// ExampleDumpFedWire loads a Fedwire file, edits the message, and writes it back.
//
// Tags are written in the order the format defines rather than the order the
// file had them, so a diff after a write-back shows lines nobody edited.
func ExampleDumpFedWire() {
dir := exampleTempDir()
defer os.RemoveAll(dir)
ctx := context.Background()
db, err := filesql.Open(context.Background(), "testdata/customer-transfer.fed")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.ExecContext(ctx,
`UPDATE customer_transfer_message SET amount = '000000012500'`); err != nil {
log.Fatal(err)
}
out := filepath.Join(dir, "edited.fed")
if err := filesql.DumpFedWire(ctx, db, "customer_transfer", out); err != nil {
log.Fatal(err)
}
reloaded, err := filesql.Open(context.Background(), out)
if err != nil {
log.Fatal(err)
}
defer reloaded.Close()
var amount string
if err := reloaded.QueryRowContext(ctx,
`SELECT amount FROM edited_message`).Scan(&amount); err != nil {
log.Fatal(err)
}
fmt.Println(amount)
// Output:
// 000000012500
}
// ExampleDumpACHWithSource writes back a database loaded from an io.Reader.
// Such a database has no file to rebuild from, so DumpACH refuses it with
// ErrSourceUnavailable; hand the same bytes over instead.
func ExampleDumpACHWithSource() {
dir := exampleTempDir()
defer os.RemoveAll(dir)
body, err := os.ReadFile("testdata/ppd-debit.ach")
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
builder := filesql.NewBuilder().
AddReader(bytes.NewReader(body), "payment", filesql.FileTypeACH)
db, err := builder.Open(ctx)
if err != nil {
log.Fatal(err)
}
defer db.Close()
out := filepath.Join(dir, "payment.ach")
err = filesql.DumpACH(ctx, db, "payment", out)
fmt.Println("without the structure:", errors.Is(err, filesql.ErrSourceUnavailable))
if _, err := db.ExecContext(ctx,
`UPDATE payment_entries SET individual_name = 'Alice Smith'`); err != nil {
log.Fatal(err)
}
if err := filesql.DumpACHWithSource(ctx, db, "payment", out, bytes.NewReader(body)); err != nil {
log.Fatal(err)
}
reloaded, err := filesql.Open(context.Background(), out)
if err != nil {
log.Fatal(err)
}
defer reloaded.Close()
var name string
if err := reloaded.QueryRowContext(ctx,
`SELECT individual_name FROM payment_entries`).Scan(&name); err != nil {
log.Fatal(err)
}
fmt.Println(name)
// Output:
// without the structure: true
// Alice Smith
}
// ExampleDumpFedWireWithSource is ExampleDumpACHWithSource for Fedwire: a
// database loaded from an io.Reader is written back by handing the export the
// same bytes.
func ExampleDumpFedWireWithSource() {
dir := exampleTempDir()
defer os.RemoveAll(dir)
body, err := os.ReadFile("testdata/customer-transfer.fed")
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
builder := filesql.NewBuilder().
AddReader(bytes.NewReader(body), "transfer", filesql.FileTypeFedWire)
db, err := builder.Open(ctx)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.ExecContext(ctx,
`UPDATE transfer_message SET amount = '000000012500'`); err != nil {
log.Fatal(err)
}
out := filepath.Join(dir, "transfer.fed")
if err := filesql.DumpFedWireWithSource(ctx, db, "transfer", out, bytes.NewReader(body)); err != nil {
log.Fatal(err)
}
reloaded, err := filesql.Open(context.Background(), out)
if err != nil {
log.Fatal(err)
}
defer reloaded.Close()
var amount string
if err := reloaded.QueryRowContext(ctx,
`SELECT amount FROM transfer_message`).Scan(&amount); err != nil {
log.Fatal(err)
}
fmt.Println(amount)
// Output:
// 000000012500
}
// ExampleDumpDatabase_deadline exports under a deadline, which is what a
// handler serving a download wants: the export stops when the request it
// belongs to does.
func ExampleDumpDatabase_deadline() {
dir, err := os.MkdirTemp("", "filesql-dump-context")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
source := filepath.Join(dir, "orders.csv")
if err := os.WriteFile(source, []byte("id,total\n1,120\n2,340\n"), 0o600); err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
db, err := filesql.Open(ctx, source)
if err != nil {
log.Fatal(err)
}
defer db.Close()
out := filepath.Join(dir, "out")
if err := filesql.DumpDatabase(ctx, db, out); err != nil {
log.Fatal(err)
}
exported, err := os.ReadFile(filepath.Join(out, "orders.csv")) //nolint:gosec // Path built from this example's own temporary directory.
if err != nil {
log.Fatal(err)
}
fmt.Print(string(exported))
// A context that is already done stops the export before it writes anything.
done, stop := context.WithCancel(context.Background())
stop()
fmt.Println(errors.Is(filesql.DumpDatabase(done, db, filepath.Join(dir, "none")), context.Canceled))
// Output:
// id,total
// 1,120
// 2,340
// true
}