-
Notifications
You must be signed in to change notification settings - Fork 4
/
importer.go
63 lines (56 loc) · 1.43 KB
/
importer.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
package psutilsql
import (
"context"
"github.com/noborus/trdsql"
)
// MultiImporter is a structure for importing multiple readers.
type MultiImporter struct {
readers []Reader
}
// Reader is an interface that can be passed to MultiImporter.
type Reader interface {
TableName() (string, error)
Names() ([]string, error)
Types() ([]string, error)
PreReadRow() [][]any
ReadRow([]any) ([]any, error)
}
// NewMultiImporter takes multiple readers as arguments and returns a MultiImporter.
func NewMultiImporter(readers ...Reader) (*MultiImporter, error) {
r := make([]Reader, len(readers))
copy(r, readers)
return &MultiImporter{
readers: readers,
}, nil
}
// ImportContext executes import.
func (i *MultiImporter) ImportContext(ctx context.Context, db *trdsql.DB, query string) (string, error) {
for _, r := range i.readers {
names, err := r.Names()
if err != nil {
return query, err
}
types, err := r.Types()
if err != nil {
return query, err
}
tableName, err := r.TableName()
if err != nil {
return query, err
}
err = db.CreateTableContext(ctx, tableName, names, types, true)
if err != nil {
return query, err
}
err = db.ImportContext(ctx, tableName, names, r)
if err != nil {
return query, err
}
}
return query, nil
}
// Import executes import.
func (i *MultiImporter) Import(db *trdsql.DB, query string) (string, error) {
ctx := context.Background()
return i.ImportContext(ctx, db, query)
}