-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
sqlx.go
214 lines (176 loc) · 5.54 KB
/
sqlx.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
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
package sqlx
import (
"context"
"database/sql"
"fmt"
"reflect"
"strings"
"unsafe"
"github.com/kataras/iris/v12/x/reflex"
)
type (
// Schema holds the row definitions.
Schema struct {
Name string
Rows map[reflect.Type]*Row
ColumnNameFunc ColumnNameFunc
AutoCloseRows bool
}
// Row holds the column definitions and the struct type & name.
Row struct {
Schema string // e.g. public
Name string // e.g. users. Must set to a custom one if the select query contains AS names.
StructType reflect.Type
Columns map[string]*Column // e.g. "id":{"id", 0, [0]}
}
// Column holds the database column name and other properties extracted by a struct's field.
Column struct {
Name string
Index int
FieldIndex []int
}
)
// NewSchema returns a new Schema. Use its Register() method to cache
// a structure value so Bind() can fill all struct's fields based on a query.
func NewSchema() *Schema {
return &Schema{
Name: "public",
Rows: make(map[reflect.Type]*Row),
ColumnNameFunc: snakeCase,
AutoCloseRows: true,
}
}
// DefaultSchema initializes a common Schema.
var DefaultSchema = NewSchema()
// Register caches a struct value to the default schema.
func Register(tableName string, value interface{}) *Schema {
return DefaultSchema.Register(tableName, value)
}
// Query is a shortcut of executing a query and bind the result to "dst".
func Query(ctx context.Context, db *sql.DB, dst interface{}, query string, args ...interface{}) error {
return DefaultSchema.Query(ctx, db, dst, query, args...)
}
// Bind sets "dst" to the result of "src" and reports any errors.
func Bind(dst interface{}, src *sql.Rows) error {
return DefaultSchema.Bind(dst, src)
}
// Register caches a struct value to the schema.
func (s *Schema) Register(tableName string, value interface{}) *Schema {
typ := reflect.TypeOf(value)
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if tableName == "" {
// convert to a human name, e.g. sqlx.Food -> food.
typeName := typ.String()
if idx := strings.LastIndexByte(typeName, '.'); idx > 0 && len(typeName) > idx {
typeName = typeName[idx+1:]
}
tableName = snakeCase(typeName)
}
columns, err := convertStructToColumns(typ, s.ColumnNameFunc)
if err != nil {
panic(fmt.Sprintf("sqlx: register: %q: %s", reflect.TypeOf(value).String(), err.Error()))
}
s.Rows[typ] = &Row{
Schema: s.Name,
Name: tableName,
StructType: typ,
Columns: columns,
}
return s
}
// Query is a shortcut of executing a query and bind the result to "dst".
func (s *Schema) Query(ctx context.Context, db *sql.DB, dst interface{}, query string, args ...interface{}) error {
rows, err := db.QueryContext(ctx, query, args...)
if err != nil {
return err
}
if !s.AutoCloseRows { // if not close on bind, we must close it here.
defer rows.Close()
}
err = s.Bind(dst, rows)
return err
}
// Bind sets "dst" to the result of "src" and reports any errors.
func (s *Schema) Bind(dst interface{}, src *sql.Rows) error {
typ := reflect.TypeOf(dst)
if typ.Kind() != reflect.Ptr {
return fmt.Errorf("sqlx: bind: destination not a pointer")
}
typ = typ.Elem()
originalKind := typ.Kind()
if typ.Kind() == reflect.Slice {
typ = typ.Elem()
}
r, ok := s.Rows[typ]
if !ok {
return fmt.Errorf("sqlx: bind: unregistered type: %q", typ.String())
}
columnTypes, err := src.ColumnTypes()
if err != nil {
return fmt.Errorf("sqlx: bind: table: %q: %w", r.Name, err)
}
if expected, got := len(r.Columns), len(columnTypes); expected != got {
return fmt.Errorf("sqlx: bind: table: %q: unexpected number of result columns: %d: expected: %d", r.Name, got, expected)
}
val := reflex.IndirectValue(reflect.ValueOf(dst))
if s.AutoCloseRows {
defer src.Close()
}
switch originalKind {
case reflect.Struct:
if src.Next() {
if err = r.bindSingle(typ, val, columnTypes, src); err != nil {
return err
}
} else {
return sql.ErrNoRows
}
return src.Err()
case reflect.Slice:
for src.Next() {
elem := reflect.New(typ).Elem()
if err = r.bindSingle(typ, elem, columnTypes, src); err != nil {
return err
}
val = reflect.Append(val, elem)
}
if err = src.Err(); err != nil {
return err
}
reflect.ValueOf(dst).Elem().Set(val)
return nil
default:
return fmt.Errorf("sqlx: bind: table: %q: unexpected destination kind: %q", r.Name, typ.Kind().String())
}
}
func (r *Row) bindSingle(typ reflect.Type, val reflect.Value, columnTypes []*sql.ColumnType, scanner interface{ Scan(...interface{}) error }) error {
fieldPtrs, err := r.lookupStructFieldPtrs(typ, val, columnTypes)
if err != nil {
return fmt.Errorf("sqlx: bind: table: %q: %w", r.Name, err)
}
return scanner.Scan(fieldPtrs...)
}
func (r *Row) lookupStructFieldPtrs(typ reflect.Type, val reflect.Value, columnTypes []*sql.ColumnType) ([]interface{}, error) {
fieldPtrs := make([]interface{}, 0, len(columnTypes))
for _, columnType := range columnTypes {
columnName := columnType.Name()
tableColumn, ok := r.Columns[columnName]
if !ok {
continue
}
// TODO: when go 1.18 released, replace with that:
/*
tableColumnField, err := val.FieldByIndexErr(tableColumn.FieldIndex)
if err != nil {
return nil, fmt.Errorf("column: %q: %w", tableColumn.Name, err)
}
*/
tableColumnField := val.FieldByIndex(tableColumn.FieldIndex)
tableColumnFieldType := tableColumnField.Type()
fieldPtr := reflect.NewAt(tableColumnFieldType, unsafe.Pointer(tableColumnField.UnsafeAddr())).Elem().Addr().Interface()
fieldPtrs = append(fieldPtrs, fieldPtr)
}
return fieldPtrs, nil
}