-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_find.go
113 lines (98 loc) · 2.4 KB
/
db_find.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
package do
import (
"context"
"database/sql"
"fmt"
"reflect"
)
type Finder[R any] interface {
// return query sql and args
Query() (query string, args []any)
// new a result type object, not the same, to receive every row
// fields must be pointer type of result object's field, and it is match with query sql's select column one by one
NewScanObjAndFields(colTypes []*sql.ColumnType) (r *R, fields []any)
}
type Storer interface {
*sql.DB | *sql.Tx | *sql.Conn
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}
func FindList[S Storer, F Finder[R], R any](db S, finder F, res *[]R) (err error) {
query, args := finder.Query()
rows, err := db.QueryContext(context.TODO(), query, args...) // sql里select了n列
if err != nil {
return
}
defer rows.Close()
colTypes, err := rows.ColumnTypes()
if err != nil {
return
}
for rows.Next() {
obj, fields := finder.NewScanObjAndFields(colTypes) // fields也必须有n个元素
if err = rows.Scan(fields...); err != nil {
return
}
// PrintFields(fields)
*res = append(*res, *obj)
}
if err = rows.Err(); err != nil {
return
}
return
}
func FindFirst[S Storer, F Finder[R], R any](db S, finder F, res *R) (err error) {
var r []R
err = FindList(db, finder, &r)
if err != nil {
return
}
if len(r) > 0 {
*res = r[0]
}
return
}
func FindAll[S Storer, F Finder[R], R any](db S, finder F, initial R) (r []R, err error) {
query, args := finder.Query()
rows, err := db.QueryContext(context.TODO(), query, args...) // sql里select了n列
if err != nil {
return
}
defer rows.Close()
colTypes, err := rows.ColumnTypes()
if err != nil {
return
}
for rows.Next() {
obj, fields := finder.NewScanObjAndFields(colTypes) // fields也必须有n个元素
if err = rows.Scan(fields...); err != nil {
return
}
// PrintFields(fields)
r = append(r, *obj)
}
if err = rows.Err(); err != nil {
return
}
return
}
func FindOne[S Storer, F Finder[R], R any](db S, finder F, initial R) (r R, err error) {
res, err := FindAll(db, finder, initial)
if err != nil {
return r, err
}
if len(res) > 0 {
r = res[0]
}
return
}
func PrintFields(fields []any) {
fmt.Println("=== begin print fields")
for i := range fields {
vall := reflect.ValueOf(fields[i])
if vall.Kind() == reflect.Pointer {
vall = vall.Elem()
}
fmt.Printf("field: %v\n", vall.Interface())
}
fmt.Println("=== end print fields")
}