repo.go 13 KB

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