-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite.go
302 lines (259 loc) · 7.45 KB
/
sqlite.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package horm
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"github.com/liucxer/hlog"
_ "github.com/mattn/go-sqlite3"
)
type DB interface {
Exec(query string, args ...interface{}) (*SqliteExecResult, error)
QueryRowInto(object interface{}, query string, args ...interface{}) error
QueryInto(object interface{}, query string, args ...interface{}) error
Close() error
}
type SqliteDB struct {
db *sql.DB
}
type SqliteExecResult struct {
LastInsertID int64
RowsAffected int64
}
func NewSqliteDB(dbPath string) (*SqliteDB, error) {
// 数据库打开
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
hlog.Error("sql.Open sqlite3 err:%+v, dbPath:%s", err, dbPath)
return nil, err
}
// 数据库连通性测试
if err = db.Ping(); err != nil {
hlog.Error("db.Ping sqlite3 err:%+v, dbPath:%s", err, dbPath)
return nil, err
}
hlog.Info("sql.Open sqlite3 err:%+v, db:%+v", err, db)
return &SqliteDB{db: db}, nil
}
func (db *SqliteDB) Close() error {
err := db.db.Close()
if err != nil {
hlog.Error("db.Close err:%+v", err)
return err
}
hlog.Info("db.Close err:%+v", err)
return err
}
func (db *SqliteDB) Exec(query string, args ...interface{}) (*SqliteExecResult, error) {
// sql语句执行
res := SqliteExecResult{}
result, err := db.db.Exec(query, args...)
if err != nil {
hlog.Error("db.Exec err:%+v, query:%s, args:%+v", err, query, args)
return nil, err
}
// 获取最后一行插入id和影响行数
res.LastInsertID, _ = result.LastInsertId()
res.RowsAffected, _ = result.RowsAffected()
hlog.Info("db.Exec err:%+v, query:%s, args:%+v, res:%+v", err, query, args, res)
return &res, err
}
type Field struct {
TagName string
Name string
Kind reflect.Kind
Value interface{}
}
type FieldList []Field
func (fieldList *FieldList) Marshal() ([]byte, error) {
tmpMap := map[string]interface{}{}
for _, field := range *fieldList {
switch field.Kind {
case reflect.Int64:
tmpMap[field.Name] = *(field.Value.(*int64))
case reflect.String:
tmpMap[field.Name] = *(field.Value.(*string))
case reflect.Float64:
tmpMap[field.Name] = *(field.Value.(*float64))
case reflect.Bool:
tmpMap[field.Name] = *(field.Value.(*bool))
default:
return nil, errors.New("unknown kind")
}
}
return json.Marshal(tmpMap)
}
type FieldLists []FieldList
func (fieldLists *FieldLists) Marshal() ([]byte, error) {
tmpMap := []map[string]interface{}{}
for _, fieldList := range *fieldLists {
itemMap := map[string]interface{}{}
for _, field := range fieldList {
switch field.Kind {
case reflect.Int64:
itemMap[field.Name] = *(field.Value.(*int64))
case reflect.String:
itemMap[field.Name] = *(field.Value.(*string))
case reflect.Float64:
itemMap[field.Name] = *(field.Value.(*float64))
case reflect.Bool:
itemMap[field.Name] = *(field.Value.(*bool))
default:
hlog.Error("unknown kind field.Kind:%d", field.Kind)
return nil, errors.New(fmt.Sprintf("unknown kind field.Kind:%d", field.Kind))
}
}
tmpMap = append(tmpMap, itemMap)
}
return json.Marshal(tmpMap)
}
func DBModelToFields(dbModel DBModel) (*[]Field, error) {
rt := reflect.TypeOf(dbModel)
if rt.Kind() != reflect.Ptr {
return nil, errors.New("dbModel must be ptr to struct")
}
rv := reflect.ValueOf(dbModel)
elem := rv.Elem()
if elem.Kind() != reflect.Struct {
return nil, errors.New("dbModel must be ptr to struct")
}
typeOfType := elem.Type()
for i := 0; i < elem.NumField(); i++ {
field := elem.Field(i)
fmt.Printf("%d. %s %s = %v ormTag:%+v \n",
i, typeOfType.Field(i).Name, field.Type(), field.Interface(), typeOfType.Field(i).Tag.Get("orm"))
}
return nil, nil
}
// 把rows中的数据转换成Field数组
func RowsToFields(rows *sql.Rows) (*[]Field, error) {
// 获取每列类型
columnTypes, err := rows.ColumnTypes()
if err != nil {
hlog.Error("rows.ColumnTypes err:%v, rows:%+v", err, rows)
return nil, err
}
res := []Field{}
var items []interface{}
for _, columnType := range columnTypes {
columnTypeName := strings.ToUpper(columnType.DatabaseTypeName())
var field Field
field.Name = strings.ToLower(columnType.Name())
switch {
case strings.HasPrefix(columnTypeName, "INT"),
strings.HasPrefix(columnTypeName, "BIGINT"):
field.Kind = reflect.Int64
value := int64(0)
field.Value = &value
items = append(items, &value)
case strings.HasPrefix(columnTypeName, "VARCHAR"),
strings.HasPrefix(columnTypeName, "TEXT"),
strings.HasPrefix(columnTypeName, "NVARCHAR"):
value := ""
field.Value = &value
field.Kind = reflect.String
items = append(items, &value)
case strings.HasPrefix(columnTypeName, "DECIMAL"),
strings.HasPrefix(columnTypeName, "FLOAT"):
value := float64(0)
field.Value = &value
field.Kind = reflect.Float64
items = append(items, &value)
case strings.HasPrefix(columnTypeName, "BOOL"):
value := false
field.Value = &value
field.Kind = reflect.Bool
items = append(items, &value)
default:
hlog.Error("unknown columnTypeName columnTypeName:%s", columnTypeName)
return nil, errors.New(fmt.Sprintf("unknown columnTypeName columnTypeName:%s", columnTypeName))
}
res = append(res, field)
}
err = rows.Scan(items...)
if err != nil {
hlog.Error("rows.Scan err:%v, rows:%+v", err, rows)
return nil, err
}
return &res, nil
}
func (db *SqliteDB) QueryRowInto(object interface{}, query string, args ...interface{}) error {
// 结果查询
rows, err := db.db.Query(query, args...)
if err != nil {
hlog.Error("db.Query err:%v, query:%s, args:%+v, row:%+v, object:%+v", err, query, args, rows, object)
return err
}
defer func() { _ = rows.Close() }()
if !rows.Next() {
hlog.Error("rows.Next is false rows:%+v", rows)
return errors.New("rows is empty")
}
fields, err := RowsToFields(rows)
if err != nil {
return err
}
fieldList := FieldList(*fields)
bts, err := fieldList.Marshal()
if err != nil {
return err
}
err = json.Unmarshal(bts, object)
if err != nil {
hlog.Error("json.Unmarshal err:%v", err)
return err
}
if rows.Next() {
hlog.Error("rows.Next is true rows:%+v", rows)
return errors.New("rows is not only one line")
}
return nil
}
func (db *SqliteDB) QueryInto(object interface{}, query string, args ...interface{}) error {
objectRV := reflect.ValueOf(object)
if objectRV.Kind() != reflect.Ptr || objectRV.IsNil() {
return errors.New("object must be ptr and not nil")
}
objectRV = objectRV.Elem()
// 结果查询
rows, err := db.db.Query(query, args...)
if err != nil {
hlog.Error("db.Query err:%v, query:%s, args:%+v, row:%+v, object:%+v", err, query, args, rows, object)
return err
}
defer func() { _ = rows.Close() }()
fieldLists := FieldLists{}
for rows.Next() {
fields, err := RowsToFields(rows)
if err != nil {
return err
}
fieldList := FieldList(*fields)
fieldLists = append(fieldLists, fieldList)
}
bts, err := fieldLists.Marshal()
if err != nil {
return err
}
err = json.Unmarshal(bts, object)
if err != nil {
return err
}
return nil
}
type DBModel interface {
TableName() string
}
func (db *SqliteDB) DropTable(model DBModel) error {
_, err := db.Exec("DROP TABLE " + strings.ToUpper(model.TableName()))
return err
}
func (db *SqliteDB) CreateTable(model DBModel) error {
_, err := db.Exec("CREATE TABLE " + strings.ToUpper(model.TableName()) + " (NAME VARCHAR(255), AGE INT(20), Height float64")
return err
}
func (db *SqliteDB) List(object interface{}, query string, args ...interface{}) error {
return db.QueryInto(object, query, args...)
}