-
Notifications
You must be signed in to change notification settings - Fork 9
/
provider.go
94 lines (83 loc) · 2.53 KB
/
provider.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
package dsunit
import (
"fmt"
"github.com/viant/dsc"
"github.com/viant/toolbox"
"strings"
)
type sequence struct {
seq map[string]int64
}
type sequenceValueProvider struct {
match string
}
func (p *sequenceValueProvider) countMatched(dataset *Dataset) int64 {
var result = 0
var keyColumn = ""
pkColumns := dataset.Records.UniqueKeys()
if len(pkColumns) > 0 {
keyColumn = pkColumns[0]
}
for _, record := range dataset.Records {
for k, v := range record {
if keyColumn != "" && strings.ToUpper(keyColumn) != strings.ToUpper(k) {
continue
}
if value, ok := v.(string); ok {
if strings.Contains(value, p.match) {
result++
}
}
}
}
return int64(result)
}
func (p *sequenceValueProvider) fetchSequence(context toolbox.Context, sequenceName string) (int64, error) {
manager := *context.GetOptional((*dsc.Manager)(nil)).(*dsc.Manager)
dataset := context.GetOptional((*Dataset)(nil)).(*Dataset)
datastoreDialect := *context.GetOptional((*dsc.DatastoreDialect)(nil)).(*dsc.DatastoreDialect)
seq, err := datastoreDialect.GetSequence(manager, sequenceName)
if err != nil {
return 0, err
}
insertableCount := p.countMatched(dataset)
result := seq - insertableCount
return result, nil
}
func (p *sequenceValueProvider) Get(context toolbox.Context, arguments ...interface{}) (interface{}, error) {
sequenceName := toolbox.AsString(arguments[0])
if !context.Contains((*sequence)(nil)) {
seq, err := p.fetchSequence(context, sequenceName)
if err != nil {
return nil, err
}
var sequenceValue = sequence{seq: make(map[string]int64)}
sequenceValue.seq[sequenceName] = seq
context.Put((*sequence)(nil), &sequenceValue)
}
var sequence = context.GetOptional((*sequence)(nil)).(*sequence)
result := sequence.seq[sequenceName]
sequence.seq[sequenceName]++
return result, nil
}
func newSequenceValueProvider(exprMatch string) toolbox.ValueProvider {
var result toolbox.ValueProvider = &sequenceValueProvider{match: exprMatch}
return result
}
type queryValueProvider struct{}
func (p *queryValueProvider) Get(context toolbox.Context, arguments ...interface{}) (interface{}, error) {
manager := *context.GetOptional((*dsc.Manager)(nil)).(*dsc.Manager)
sql := toolbox.AsString(arguments[0])
var row = make([]interface{}, 0)
success, err := manager.ReadSingle(&row, sql, nil, nil)
if err != nil {
return nil, fmt.Errorf("failed to evalue macro with sql: %v, %v", sql, err)
}
if !success {
return nil, nil
}
return row[0], nil
}
func newQueryValueProvider() toolbox.ValueProvider {
return &queryValueProvider{}
}