-
Notifications
You must be signed in to change notification settings - Fork 3
/
qmgo.go
571 lines (494 loc) · 16.5 KB
/
qmgo.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
package qmgo
import (
"context"
"fmt"
"regexp"
"strings"
"github.com/zhufuyi/pkg/logger"
"github.com/qiniu/qmgo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
var (
defaultClient *DefaultClient
// ErrNotFoundStr 错误
ErrNotFoundStr = qmgo.ErrNoSuchDocuments.Error()
)
// Clienter 提供外部调用的接口
type Clienter interface {
WithLog() Clienter
Close() error
Insert(collection string, doc interface{}) error
InsertMany(collection string, docs []interface{}) error
FindOne(collection string, result interface{}, query bson.M, fields bson.M) error
FindAll(collection string, result interface{}, query bson.M, fields bson.M, skip int64, limit int64, sort ...string) error
UpdateOne(collection string, query bson.M, update bson.M) error
UpdateAll(collection string, query bson.M, update bson.M) (int64, error)
DeleteOne(collection string, query bson.M) error
DeleteAll(collection string, query bson.M) (int64, error)
DeleteOneCompletely(collection string, query bson.M) error
DeleteAllCompletely(collection string, query bson.M) (int64, error)
Count(collection string, query bson.M) (int64, error)
CountAll(collection string, query bson.M) (int64, error)
EnsureIndexes(collection string, indexes []string) error
EnsureUniques(collection string, uniques []string) error
Aggregate(collection string, matchStage primitive.D, groupStage primitive.D) ([]bson.M, error)
Transaction(collection string, callback func(sessCtx context.Context) (interface{}, error)) (interface{}, error)
GetQmgoClient(collection string) *qmgo.QmgoClient
}
// GetCli 获取新的session,使用前先调用函数InitToGlobal,否则抛出异常
func GetCli() Clienter {
if defaultClient == nil {
panic("mongodb session is nil, go to connect mongodb first, eg: mongo.InitToGlobal(uri)")
}
return &DefaultClient{
ctx: defaultClient.ctx,
mdbName: defaultClient.mdbName,
cli: defaultClient.cli,
printLog: defaultClient.printLog,
}
//return defaultClient
}
// InitToGlobal 初始化mongodb,全局使用,只适用对单个mongodb操作,如果不指定数据库,默认数据库名为test
//
// 形式一:localhost 或 localhost:27017
// 形式二:mongodb://localhost:27017/database_name 或 mongodb://localhost1:port,localhost2:port/database_name
// 形式三:mongodb://user:password@localhost:27017/database_name 或 mongodb://user:password@localhost1:port,localhost2:port/database_name
func InitToGlobal(url string) error {
ctx := context.Background()
client, err := qmgo.NewClient(ctx, &qmgo.Config{Uri: url})
if err != nil {
return err
}
dbName := getDBName(url)
defaultClient = &DefaultClient{
ctx: ctx,
mdbName: dbName,
cli: client,
}
return client.Ping(10)
}
// Init 初始化mongodb,使用对多个mongodb独立操作,如果不指定数据库,默认数据库名为test
func Init(url string) (string, Clienter, error) {
ctx := context.Background()
client, err := qmgo.NewClient(ctx, &qmgo.Config{Uri: url})
if err != nil {
return "", nil, err
}
dbName := getDBName(url)
dc := &DefaultClient{
ctx: ctx,
mdbName: dbName,
cli: client,
}
return dbName, dc, client.Ping(10)
}
// -------------------------------------------------------------------------------------------------
// DefaultClient mgo的客户端对象
type DefaultClient struct {
ctx context.Context // 上下文
mdbName string // 数据库名称
cli *qmgo.Client // 客户端
printLog bool // 是否打印执行命令信息
}
// WithLog 打印执行命令
func (d *DefaultClient) WithLog() Clienter {
d.printLog = true
return d
}
// Close 关闭连接
func (d *DefaultClient) Close() error {
return d.cli.Close(d.ctx)
}
// Insert 插入一条新数据
func (d *DefaultClient) Insert(collection string, doc interface{}) error {
_, err := d.cli.Database(d.mdbName).Collection(collection).InsertOne(d.ctx, doc)
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.insert", d.mdbName, collection)),
logger.Any("content", doc),
).Warn("mongodb insert failed.")
}
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.insert", d.mdbName, collection)),
logger.Any("content", doc),
).Info("mongodb insert success.")
}
return nil
}
// InsertMany 插入多条新数据
func (d *DefaultClient) InsertMany(collection string, docs []interface{}) error {
_, err := d.cli.Database(d.mdbName).Collection(collection).InsertMany(d.ctx, docs)
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.insert", d.mdbName, collection)),
logger.Any("content", docs),
).Warn("mongodb insert failed.")
}
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.insert", d.mdbName, collection)),
logger.Any("content", docs),
).Info("mongodb insert success.")
}
return nil
}
// FindOne 查找一条记录
func (d *DefaultClient) FindOne(collection string, result interface{}, query bson.M, fields bson.M) error {
err := d.cli.Database(d.mdbName).Collection(collection).Find(d.ctx, ExcludeDeleted(query)).Select(fields).One(result)
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.findOne", d.mdbName, collection)),
logger.Any("query", query),
logger.Any("fields", fields),
).Warn("mongodb find one failed.")
}
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.findOne", d.mdbName, collection)),
logger.Any("query", query),
logger.Any("fields", fields),
logger.Any("result", result),
).Info("mongodb find one success.")
}
return nil
}
// FindAll 查找符合条件的多条记录,这里参数skip表示页码,limit表示每页多少行数据
func (d *DefaultClient) FindAll(collection string, result interface{}, query bson.M, fields bson.M, page int64, limit int64, sort ...string) error {
err := d.cli.Database(d.mdbName).Collection(collection).Find(d.ctx, ExcludeDeleted(query)).Select(fields).Sort(sort...).Skip(page * limit).Limit(limit).All(result)
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.find", d.mdbName, collection)),
logger.Any("query", query),
logger.Any("fields", fields),
logger.Int64("page", page),
logger.Int64("limit", limit),
logger.Any("sort", sort),
).Warn("mongodb find all failed.")
}
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.find", d.mdbName, collection)),
logger.Any("query", query),
logger.Any("fields", fields),
logger.Int64("page", page),
logger.Int64("limit", limit),
logger.Any("sort", sort),
logger.Any("result", result),
).Info("mongodb find all success.")
}
return nil
}
// UpdateOne 更新一条记录
func (d *DefaultClient) UpdateOne(collection string, query bson.M, update bson.M) error {
err := CheckUpdateContent(update)
if err != nil {
return err
}
err = d.cli.Database(d.mdbName).Collection(collection).UpdateOne(d.ctx, ExcludeDeleted(query), UpdatedTime(update))
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.update", d.mdbName, collection)),
logger.Any("query", query),
logger.Any("update", update),
).Warn("mongodb update one failed.")
}
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.update", d.mdbName, collection)),
logger.Any("query", query),
logger.Any("update", update),
).Info("mongodb update one success.")
}
return nil
}
// UpdateAll 更新所有匹配的记录
func (d *DefaultClient) UpdateAll(collection string, query bson.M, update bson.M) (int64, error) {
err := CheckUpdateContent(update)
if err != nil {
return 0, err
}
updateResult, err := d.cli.Database(d.mdbName).Collection(collection).UpdateAll(d.ctx, ExcludeDeleted(query), UpdatedTime(update))
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.updateAll", d.mdbName, collection)),
logger.Any("query", query),
logger.Any("update", update),
).Warn("mongodb update all failed.")
}
return 0, err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.updateAll", d.mdbName, collection)),
logger.Any("query", query),
logger.Any("update", update),
logger.Int64("updatedNum", updateResult.ModifiedCount),
).Info("mongodb update all success.")
}
return updateResult.ModifiedCount, nil
}
// DeleteOne 标记性删除一条记录
func (d *DefaultClient) DeleteOne(collection string, query bson.M) error {
err := d.cli.Database(d.mdbName).Collection(collection).UpdateOne(d.ctx, ExcludeDeleted(query), DeletedTime(bson.M{}))
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.update", d.mdbName, collection)),
logger.Any("query", query),
).Warn("mongodb markup delete one failed.")
}
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.remove", d.mdbName, collection)),
logger.Any("query", query),
).Info("mongodb markup delete one success.")
}
return nil
}
// DeleteAll 标记性删除所有匹配的记录
func (d *DefaultClient) DeleteAll(collection string, query bson.M) (int64, error) {
updateResult, err := d.cli.Database(d.mdbName).Collection(collection).UpdateAll(d.ctx, ExcludeDeleted(query), DeletedTime(bson.M{}))
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.remove", d.mdbName, collection)),
logger.Any("query", query),
).Warn("mongodb markup delete all failed.")
}
return 0, err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.remove", d.mdbName, collection)),
logger.Any("query", query),
logger.Int64("removedNum", updateResult.ModifiedCount),
).Info("mongodb markup delete all success.")
}
return updateResult.ModifiedCount, nil
}
// DeleteOneCompletely 删除一条记录,包括标记性删除的记录
func (d *DefaultClient) DeleteOneCompletely(collection string, query bson.M) error {
err := d.cli.Database(d.mdbName).Collection(collection).Remove(d.ctx, query)
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.remove", d.mdbName, collection)),
logger.Any("query", query),
).Warn("mongodb delete one failed.")
}
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.remove", d.mdbName, collection)),
logger.Any("query", query),
).Info("mongodb delete one success.")
}
return nil
}
// DeleteAllCompletely 删除所有匹配的记录,包括标记性删除的记录
func (d *DefaultClient) DeleteAllCompletely(collection string, query bson.M) (int64, error) {
deleteResult, err := d.cli.Database(d.mdbName).Collection(collection).RemoveAll(d.ctx, query)
if err != nil {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.remove", d.mdbName, collection)),
logger.Any("query", query),
).Warn("mongodb real delete all failed.")
}
return 0, err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.remove", d.mdbName, collection)),
logger.Any("query", query),
logger.Int64("removedNum", deleteResult.DeletedCount),
).Info("mongodb real delete all success.")
}
return deleteResult.DeletedCount, nil
}
// Count 统计匹配的数量,不包括标记性删除的记录
func (d *DefaultClient) Count(collection string, query bson.M) (int64, error) {
count, err := d.cli.Database(d.mdbName).Collection(collection).Find(d.ctx, ExcludeDeleted(query)).Count()
if err != nil && err.Error() != ErrNotFoundStr {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.count", d.mdbName, collection)),
logger.Any("query", query),
).Warn("mongodb count failed.")
}
return 0, err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.count", d.mdbName, collection)),
logger.Any("query", query),
logger.Int64("count", count),
).Info("mongodb count success.")
}
return count, nil
}
// CountAll 统计匹配的数量,包括标记性删除的记录
func (d *DefaultClient) CountAll(collection string, query bson.M) (int64, error) {
count, err := d.cli.Database(d.mdbName).Collection(collection).Find(d.ctx, query).Count()
if err != nil && err.Error() != ErrNotFoundStr {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.count", d.mdbName, collection)),
logger.Any("query", query),
).Warn("mongodb count all failed.")
}
return 0, err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.count", d.mdbName, collection)),
logger.Any("query", query),
logger.Int64("count", count),
).Info("mongodb count all success.")
}
return count, nil
}
// EnsureIndexes 设置普通索引
func (d *DefaultClient) EnsureIndexes(collection string, indexes []string) error {
err := d.cli.Database(d.mdbName).Collection(collection).EnsureIndexes(d.ctx, []string{}, indexes)
if err != nil {
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.ensureIndexes", d.mdbName, collection)),
logger.Any("indexes", indexes),
).Info("mongodb set index key success.")
}
return nil
}
// EnsureUniques 设置唯一索引
func (d *DefaultClient) EnsureUniques(collection string, uniques []string) error {
err := d.cli.Database(d.mdbName).Collection(collection).EnsureIndexes(d.ctx, uniques, []string{})
if err != nil {
return err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.ensureUniques", d.mdbName, collection)),
logger.Any("uniques", uniques),
).Info("mongodb set uniques key success.")
}
return nil
}
// Aggregate 聚合查询
func (d *DefaultClient) Aggregate(collection string, matchStage primitive.D, groupStage primitive.D) ([]bson.M, error) {
var showsWithInfo []bson.M
err := d.cli.Database(d.mdbName).Collection(collection).Aggregate(d.ctx, qmgo.Pipeline{matchStage, groupStage}).All(&showsWithInfo)
if err != nil && err.Error() != ErrNotFoundStr {
if d.printLog {
d.printLog = false
logger.WithFields(
logger.Err(err),
logger.String("command", fmt.Sprintf("%s.%s.count", d.mdbName, collection)),
logger.Any("matchStage", matchStage),
logger.Any("groupStage", groupStage),
).Warn("mongodb aggregate failed.")
}
return nil, err
}
if d.printLog {
d.printLog = false
logger.WithFields(
logger.String("command", fmt.Sprintf("%s.%s.count", d.mdbName, collection)),
logger.Any("matchStage", matchStage),
logger.Any("groupStage", groupStage),
logger.Any("showsWithInfo", showsWithInfo),
).Info("mongodb aggregate success.")
}
return showsWithInfo, nil
}
// GetQmgoClient 获取client对象
func (d *DefaultClient) GetQmgoClient(collection string) *qmgo.QmgoClient {
db := d.cli.Database(d.mdbName)
coll := db.Collection(collection)
cli := &qmgo.QmgoClient{
Collection: coll,
Database: db,
Client: d.cli,
}
return cli
}
// Transaction 事务
func (d *DefaultClient) Transaction(collection string, callback func(sessCtx context.Context) (interface{}, error)) (interface{}, error) {
db := d.cli.Database(d.mdbName)
coll := db.Collection(collection)
cli := &qmgo.QmgoClient{
Collection: coll,
Database: db,
Client: d.cli,
}
return cli.DoTransaction(d.ctx, callback)
}
func getDBName(url string) string {
url = strings.Trim(url, "/")
matches := regexp.MustCompile(`mongodb://[^/]+/(.*)`).FindAllSubmatch([]byte(url), -1)
for _, match := range matches {
return string(match[1])
}
return "test"
}