repo.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. package repo
  2. import (
  3. "box-cost/db"
  4. "box-cost/log"
  5. "context"
  6. "fmt"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/bson/primitive"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. "go.mongodb.org/mongo-driver/mongo/options"
  11. )
  12. type RepoSession struct {
  13. Ctx context.Context
  14. Client *db.MongoDB
  15. }
  16. const (
  17. CollectionDatabase = "database"
  18. CollectionAssetCount = "assetcount"
  19. )
  20. type Map map[string]interface{}
  21. type PageResult struct {
  22. List []map[string]interface{} `json:"list"`
  23. Total int64 `json:"total"`
  24. Page int64 `json:"page"`
  25. Size int64 `json:"size"`
  26. }
  27. type PageSearchOptions struct {
  28. Db string
  29. CollectName string
  30. Page int64
  31. Size int64
  32. Query map[string]interface{}
  33. Project []string
  34. Sort interface{}
  35. }
  36. type DocSearchOptions struct {
  37. Db string
  38. CollectName string
  39. Query Map
  40. Project []string
  41. Sort bson.M
  42. }
  43. func NewDocSearchOptions(filter Map, project []string) *DocSearchOptions {
  44. return &DocSearchOptions{
  45. Query: filter,
  46. Project: project,
  47. }
  48. }
  49. func RepoAddDoc(ctx *RepoSession, collectName string, doc interface{}) (string, error) {
  50. users := ctx.Client.GetCollection(collectName)
  51. result, err := users.InsertOne(ctx.Ctx, doc)
  52. if err != nil {
  53. return "", err
  54. }
  55. return result.InsertedID.(primitive.ObjectID).Hex(), nil
  56. }
  57. func RepoDbAddDoc(ctx *RepoSession, dbName string, collectName string, doc interface{}) (string, error) {
  58. users := ctx.Client.GetDbCollection(dbName, collectName)
  59. result, err := users.InsertOne(ctx.Ctx, doc)
  60. if err != nil {
  61. return "", err
  62. }
  63. return result.InsertedID.(primitive.ObjectID).Hex(), nil
  64. }
  65. func RepoDeleteDoc(ctx *RepoSession, collectName string, id string) (interface{}, error) {
  66. uid, _ := primitive.ObjectIDFromHex(id)
  67. colls := ctx.Client.GetCollection(collectName)
  68. return colls.DeleteOne(ctx.Ctx, &bson.M{"_id": uid})
  69. }
  70. func RepoDeleteDbDoc(ctx *RepoSession, dbName string, collectName string, id string) (interface{}, error) {
  71. uid, _ := primitive.ObjectIDFromHex(id)
  72. colls := ctx.Client.GetDbCollection(dbName, collectName)
  73. return colls.DeleteOne(ctx.Ctx, &bson.M{"_id": uid})
  74. }
  75. func RepoDeleteDocs(ctx *RepoSession, collectName string, query interface{}) (interface{}, error) {
  76. colls := ctx.Client.GetCollection(collectName)
  77. return colls.DeleteMany(ctx.Ctx, query)
  78. }
  79. func RepoUpdateSetDoc(ctx *RepoSession, collectName string, idstr string, model interface{}) (*mongo.UpdateResult, error) {
  80. colls := ctx.Client.GetCollection(collectName)
  81. update := bson.M{"$set": model}
  82. uid, _ := primitive.ObjectIDFromHex(idstr)
  83. return colls.UpdateByID(ctx.Ctx, uid, update)
  84. }
  85. func RepoUpdateSeDbDoc(ctx *RepoSession, db string, collectName string, idstr string, model interface{}) (*mongo.UpdateResult, error) {
  86. colls := ctx.Client.GetDbCollection(db, collectName)
  87. update := bson.M{"$set": model}
  88. uid, _ := primitive.ObjectIDFromHex(idstr)
  89. return colls.UpdateByID(ctx.Ctx, uid, update)
  90. }
  91. func RepoUpdateSetDocProps(ctx *RepoSession, collectName string, idstr string, update interface{}) (*mongo.UpdateResult, error) {
  92. colls := ctx.Client.GetCollection(collectName)
  93. // update := bson.M{"$set": model}
  94. uid, _ := primitive.ObjectIDFromHex(idstr)
  95. return colls.UpdateByID(ctx.Ctx, uid, update)
  96. }
  97. func RepoUpdateSetDbDocProps(ctx *RepoSession, db string, collectName string, idstr string, update interface{}) (*mongo.UpdateResult, error) {
  98. colls := ctx.Client.GetDbCollection(db, collectName)
  99. // update := bson.M{"$set": model}
  100. uid, _ := primitive.ObjectIDFromHex(idstr)
  101. return colls.UpdateByID(ctx.Ctx, uid, update)
  102. }
  103. func RepoSeachDoc(ctx *RepoSession, param *DocSearchOptions, v interface{}) (bool, error) {
  104. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  105. opt := &options.FindOneOptions{}
  106. if len(param.Project) > 0 {
  107. prj := bson.M{}
  108. for _, v := range param.Project {
  109. prj[v] = 1
  110. }
  111. opt.SetProjection(prj)
  112. }
  113. filter := bson.M{}
  114. if len(param.Query) > 0 {
  115. for k, v := range param.Query {
  116. if k == "_id" {
  117. if uid, ok := v.(string); ok {
  118. docId, _ := primitive.ObjectIDFromHex(uid)
  119. filter["_id"] = docId
  120. continue
  121. }
  122. }
  123. filter[k] = v
  124. }
  125. }
  126. err := colls.FindOne(ctx.Ctx, filter, opt).Decode(v)
  127. if err == mongo.ErrNoDocuments {
  128. return false, nil
  129. }
  130. if err != nil {
  131. return false, err
  132. }
  133. return true, nil
  134. }
  135. func RepoSeachDocMap(ctx *RepoSession, param *DocSearchOptions) (bool, map[string]interface{}) {
  136. ret := map[string]interface{}{}
  137. ok := true
  138. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  139. opt := &options.FindOneOptions{}
  140. if len(param.Project) > 0 {
  141. prj := bson.M{}
  142. for _, v := range param.Project {
  143. prj[v] = 1
  144. }
  145. opt.SetProjection(prj)
  146. }
  147. filter := bson.M{}
  148. if len(param.Query) > 0 {
  149. for k, v := range param.Query {
  150. if k == "_id" {
  151. if uid, ok := v.(string); ok {
  152. docId, _ := primitive.ObjectIDFromHex(uid)
  153. filter["_id"] = docId
  154. continue
  155. }
  156. }
  157. filter[k] = v
  158. }
  159. }
  160. ok = true
  161. err := colls.FindOne(ctx.Ctx, filter, opt).Decode(ret)
  162. if err == mongo.ErrNoDocuments {
  163. ok = false
  164. }
  165. if err != nil {
  166. ok = false
  167. }
  168. return ok, ret
  169. }
  170. // PageSearch 单表分页查询
  171. func RepoPageSearch(ctx *RepoSession, para *PageSearchOptions) (out *PageResult, err error) {
  172. var colls *mongo.Collection
  173. if len(para.Db) > 0 {
  174. colls = ctx.Client.GetDbCollection(para.Db, para.CollectName)
  175. } else {
  176. colls = ctx.Client.GetCollection(para.CollectName)
  177. }
  178. findoptions := &options.FindOptions{}
  179. if para.Size > 0 {
  180. findoptions.SetLimit(para.Size)
  181. findoptions.SetSkip(para.Size * (para.Page - 1))
  182. }
  183. if para.Sort != nil {
  184. findoptions.SetSort(para.Sort)
  185. }
  186. if len(para.Project) > 0 {
  187. prj := bson.M{}
  188. for _, v := range para.Project {
  189. prj[v] = 1
  190. }
  191. findoptions.SetProjection(prj)
  192. }
  193. filter := bson.M{}
  194. if len(para.Query) > 0 {
  195. for k, v := range para.Query {
  196. if value, ok := v.(string); ok {
  197. if len(value) > 0 {
  198. filter[k] = v
  199. continue
  200. }
  201. } else if v != nil {
  202. filter[k] = v
  203. }
  204. }
  205. }
  206. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  207. out = &PageResult{
  208. List: []map[string]interface{}{},
  209. Total: 0,
  210. Page: para.Page,
  211. Size: para.Size,
  212. }
  213. if err != nil {
  214. return out, err
  215. }
  216. defer cur.Close(ctx.Ctx)
  217. err = cur.All(ctx.Ctx, &out.List)
  218. out.Total, _ = colls.CountDocuments(ctx.Ctx, filter)
  219. return
  220. }
  221. func RepoDbCountDoc(ctx *RepoSession, db string, collectionName string, Query Map) (int64, error) {
  222. colls := ctx.Client.GetDbCollection(db, collectionName)
  223. filter := bson.M{}
  224. if len(Query) > 0 {
  225. for k, v := range Query {
  226. if value, ok := v.(string); ok {
  227. if len(value) > 0 {
  228. filter[k] = v
  229. continue
  230. }
  231. } else {
  232. filter[k] = v
  233. }
  234. }
  235. }
  236. return colls.CountDocuments(ctx.Ctx, filter)
  237. }
  238. func RepoCountDoc(ctx *RepoSession, collectionName string, Query Map) (int64, error) {
  239. colls := ctx.Client.GetCollection(collectionName)
  240. filter := bson.M{}
  241. if len(Query) > 0 {
  242. for k, v := range Query {
  243. if value, ok := v.(string); ok {
  244. if len(value) > 0 {
  245. filter[k] = v
  246. continue
  247. }
  248. } else {
  249. filter[k] = v
  250. }
  251. }
  252. }
  253. return colls.CountDocuments(ctx.Ctx, filter)
  254. }
  255. // PageSearch 单表分页查询
  256. func RepoDocsSearch(ctx *RepoSession, para *PageSearchOptions, out interface{}) (err error) {
  257. colls := ctx.Client.GetCollection(para.CollectName)
  258. if len(para.Db) > 0 {
  259. colls = ctx.Client.GetDbCollection(para.Db, para.CollectName)
  260. }
  261. findoptions := &options.FindOptions{}
  262. if para.Size > 0 {
  263. findoptions.SetLimit(para.Size)
  264. findoptions.SetSkip(para.Size * (para.Page - 1))
  265. }
  266. if para.Sort != nil {
  267. findoptions.SetSort(para.Sort)
  268. }
  269. if len(para.Project) > 0 {
  270. prj := bson.M{}
  271. for _, v := range para.Project {
  272. prj[v] = 1
  273. }
  274. findoptions.SetProjection(prj)
  275. }
  276. filter := bson.M{}
  277. if len(para.Query) > 0 {
  278. for k, v := range para.Query {
  279. if value, ok := v.(string); ok {
  280. if len(value) > 0 {
  281. filter[k] = v
  282. continue
  283. }
  284. } else {
  285. filter[k] = v
  286. }
  287. }
  288. }
  289. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  290. if err != nil {
  291. return err
  292. }
  293. defer cur.Close(ctx.Ctx)
  294. err = cur.All(ctx.Ctx, out)
  295. return
  296. }
  297. func RepoDocArrayAppend(ctx *RepoSession, collectName string, idstr string, fieldpath string, arrayItem interface{}) (*mongo.UpdateResult, error) {
  298. colls := ctx.Client.GetCollection(collectName)
  299. arrayOp := bson.M{}
  300. arrayOp[fieldpath] = arrayItem
  301. update := bson.M{"$push": arrayOp}
  302. uid, _ := primitive.ObjectIDFromHex(idstr)
  303. return colls.UpdateByID(ctx.Ctx, uid, update)
  304. }
  305. // { _id: 4, "grades.grade": 85 },
  306. // { $set: { "grades.$.std" : 6 } }
  307. type ArrayOneUpdateOption struct {
  308. Query Map
  309. Set Map
  310. CollectName string
  311. Id string
  312. }
  313. // if len(scene.Stickers) > 0 {
  314. // optSet["scenes.$.stickers"] = scene.Stickers
  315. // }
  316. // option := &repo.ArrayOneUpdateOption{
  317. // CollectName: repo.CollectionDesigns,
  318. // Id: id,
  319. // Query: repo.Map{"scenes.id": scene.Id},
  320. // Set: optSet,
  321. // }
  322. func RepoDocArrayOneUpdate(ctx *RepoSession, options *ArrayOneUpdateOption) (*mongo.UpdateResult, error) {
  323. colls := ctx.Client.GetCollection(options.CollectName)
  324. docId, _ := primitive.ObjectIDFromHex(options.Id)
  325. query := bson.M{"_id": docId}
  326. if len(options.Query) > 0 {
  327. for k, v := range options.Query {
  328. query[k] = v
  329. }
  330. }
  331. setOp := bson.M{}
  332. for k, v := range options.Set {
  333. setOp[k] = v
  334. }
  335. update := bson.M{"$set": setOp}
  336. return colls.UpdateOne(ctx.Ctx, query, update)
  337. }
  338. type ArrayOneRemoveOption struct {
  339. ArrayQuery Map
  340. CollectName string
  341. Id string
  342. }
  343. // { $pull: { "items" : { id: 23 } } }
  344. func RepoDocArrayOneRemove(ctx *RepoSession, options *ArrayOneRemoveOption) (*mongo.UpdateResult, error) {
  345. colls := ctx.Client.GetCollection(options.CollectName)
  346. docId, _ := primitive.ObjectIDFromHex(options.Id)
  347. query := bson.M{"_id": docId}
  348. arrayQuery := bson.M{}
  349. if len(options.ArrayQuery) > 0 {
  350. for k, v := range options.ArrayQuery {
  351. arrayQuery[k] = v
  352. }
  353. }
  354. update := bson.M{"$pull": arrayQuery}
  355. return colls.UpdateOne(ctx.Ctx, query, update)
  356. }
  357. type ArrayOneSearchOption struct {
  358. ArrayQuery Map
  359. CollectName string
  360. Id string
  361. Field string
  362. }
  363. func RepoDocArraySearch(ctx *RepoSession, options *ArrayOneSearchOption, entity interface{}) error {
  364. colls := ctx.Client.GetCollection(options.CollectName)
  365. docId, _ := primitive.ObjectIDFromHex(options.Id)
  366. match := []bson.E{}
  367. match = append(match, bson.E{"_id", docId})
  368. matchStage := bson.D{
  369. {"$match", match},
  370. }
  371. unwindStage := bson.D{
  372. {"$unwind", fmt.Sprintf("%s%s", "$", options.Field)},
  373. }
  374. pipe := mongo.Pipeline{matchStage, unwindStage}
  375. if len(options.ArrayQuery) > 0 {
  376. match2 := []bson.E{}
  377. for k, v := range options.ArrayQuery {
  378. match2 = append(match2, bson.E{k, v})
  379. }
  380. match2Stage := bson.D{
  381. {"$match", match2},
  382. }
  383. pipe = append(pipe, match2Stage)
  384. }
  385. curr, err := colls.Aggregate(ctx.Ctx, pipe)
  386. if err != nil {
  387. return err
  388. }
  389. defer curr.Close(ctx.Ctx)
  390. if curr.Next(ctx.Ctx) {
  391. err = curr.Decode(entity)
  392. if err != nil {
  393. return err
  394. }
  395. return nil
  396. }
  397. return nil
  398. }
  399. type DocsSearchOptions struct {
  400. CollectName string
  401. Query map[string]interface{}
  402. Project []string
  403. Sort interface{} //bson.D{ bson.E{"update_time", -1}, bson.E{"goods_id", -1},}
  404. }
  405. func RepoSeachDocsMap(ctx *RepoSession, param *DocsSearchOptions) (ok bool, list []map[string]interface{}) {
  406. colls := ctx.Client.GetCollection(param.CollectName)
  407. findoptions := &options.FindOptions{}
  408. if len(param.Project) > 0 {
  409. prj := bson.M{}
  410. for _, v := range param.Project {
  411. prj[v] = 1
  412. }
  413. findoptions.SetProjection(prj)
  414. }
  415. if param.Sort != nil {
  416. findoptions.SetSort(param.Sort)
  417. }
  418. filter := bson.M{}
  419. if len(param.Query) > 0 {
  420. for k, v := range param.Query {
  421. if value, ok := v.(string); ok {
  422. if len(value) > 0 {
  423. filter[k] = v
  424. continue
  425. }
  426. } else {
  427. filter[k] = v
  428. }
  429. }
  430. }
  431. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  432. if err != nil {
  433. ok = false
  434. return
  435. }
  436. defer cur.Close(ctx.Ctx)
  437. listRes := []map[string]interface{}{}
  438. err = cur.All(ctx.Ctx, &listRes)
  439. if err != nil {
  440. log.Error(err)
  441. ok = false
  442. return
  443. }
  444. list = listRes
  445. ok = true
  446. return
  447. }
  448. type DbDocsSearchOptions struct {
  449. Db string
  450. CollectName string
  451. Query map[string]interface{}
  452. Project []string
  453. Sort interface{} //bson.D{ bson.E{"update_time", -1}, bson.E{"goods_id", -1},}
  454. }
  455. func DbRepoSeachDocsMap(ctx *RepoSession, param *DbDocsSearchOptions) (ok bool, list []map[string]interface{}) {
  456. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  457. findoptions := &options.FindOptions{}
  458. if len(param.Project) > 0 {
  459. prj := bson.M{}
  460. for _, v := range param.Project {
  461. prj[v] = 1
  462. }
  463. findoptions.SetProjection(prj)
  464. }
  465. if param.Sort != nil {
  466. findoptions.SetSort(param.Sort)
  467. }
  468. filter := bson.M{}
  469. if len(param.Query) > 0 {
  470. for k, v := range param.Query {
  471. if value, ok := v.(string); ok {
  472. if len(value) > 0 {
  473. filter[k] = v
  474. continue
  475. }
  476. } else {
  477. filter[k] = v
  478. }
  479. }
  480. }
  481. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  482. if err != nil {
  483. ok = false
  484. return
  485. }
  486. defer cur.Close(ctx.Ctx)
  487. listRes := []map[string]interface{}{}
  488. err = cur.All(ctx.Ctx, &listRes)
  489. if err != nil {
  490. log.Error(err)
  491. ok = false
  492. return
  493. }
  494. list = listRes
  495. ok = true
  496. return
  497. }