forked from mattn/go-oci8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlrows_test.go
130 lines (108 loc) · 2.18 KB
/
sqlrows_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
package oci8
import (
"database/sql"
"fmt"
)
type RowMap struct {
columns []string
byName map[string]int
values []interface{}
rows *sql.Rows
}
func NewS(r *sql.Rows, e error) (*RowMap, error) {
if e != nil {
return nil, e
}
rm := &RowMap{rows: r}
e = rm.init()
if e != nil {
return nil, e
}
return rm, nil
}
func (r *RowMap) Key(key string) interface{} {
if v, ok := r.Get(key); ok {
return v
}
return nil
}
func (r *RowMap) Get(key string) (interface{}, bool) {
if i, ok := r.byName[key]; ok {
return r.values[i], true
}
return nil, false
}
func (r *RowMap) Row() []interface{} {
return r.values
}
func (r *RowMap) Map() map[string]interface{} {
ret := make(map[string]interface{}, len(r.columns))
for i, v := range r.columns {
ret[v] = r.values[i]
}
return ret
}
func (r *RowMap) Next() bool {
return r.rows.Next()
}
func (r *RowMap) Err() error {
return r.rows.Err()
}
func (r *RowMap) Close() error {
r.values = r.values[:0]
r.columns = nil
r.byName = nil
return r.rows.Close()
}
func (r *RowMap) Init(rows *sql.Rows) error {
if r.columns != nil {
panic("must be closed first")
}
r.rows = rows
return r.init()
}
func (r *RowMap) init() error {
var err error
r.columns, err = r.rows.Columns()
if err != nil {
return err
}
delta := len(r.columns) - len(r.values)
if delta > 0 {
r.values = append(r.values, make([]interface{}, delta)...)
} else if delta < 0 {
r.values = r.values[:len(r.columns)]
}
r.byName = make(map[string]int, len(r.columns))
for i, key := range r.columns {
r.byName[key] = i
}
return nil
}
func (r *RowMap) Scan() error {
for i := range r.values {
r.values[i] = &r.values[i]
}
return r.rows.Scan(r.values...)
}
func (r *RowMap) Print() {
for i, v := range r.columns {
switch z := r.values[i].(type) {
case string:
if len(z) > 40 {
fmt.Printf("%s=[%d]%v...%v.\n", v, len(z), z[:10], z[len(z)-10:])
} else {
fmt.Printf("%s=[%d]%v.\n", v, len(z), z)
}
case []byte:
if len(z) > 40 {
fmt.Printf("%s=[%d]%v...%v.\n", v, len(z), z[:10], z[len(z)-10:])
} else {
fmt.Printf("%s=[%d]%v.\n", v, len(z), z)
}
default:
fmt.Printf("%s=%v.\n", v, r.values[i])
}
}
fmt.Println()
}