Prepare for v3

main
Nikita Tokarchuk 4 months ago
parent 7c3e50e783
commit 23029ae710
Signed by: mainnika
GPG Key ID: 5CDEED14F48FA79D
  1. 4
      go.mod
  2. 55
      go.sum
  3. 12
      mongox-testing/database/ephemeral.go
  4. 44
      mongox/base/docbased/id.go
  5. 26
      mongox/base/docbased/id_test.go
  6. 66
      mongox/base/getid.go
  7. 22
      mongox/base/getid_test.go
  8. 40
      mongox/base/getprotection.go
  9. 16
      mongox/base/ifacebased/id.go
  10. 24
      mongox/base/jsonbased/id.go
  11. 19
      mongox/base/oidbased/id.go
  12. 18
      mongox/base/oidbased/id_test.go
  13. 38
      mongox/base/protection/key.go
  14. 3
      mongox/base/protection/key_test.go
  15. 1
      mongox/base/reset.go
  16. 14
      mongox/base/stringbased/id.go
  17. 14
      mongox/base/stringbased/id_test.go
  18. 23
      mongox/database/context.go
  19. 19
      mongox/database/count.go
  20. 188
      mongox/database/cursor.go
  21. 220
      mongox/database/database.go
  22. 50
      mongox/database/deletearray.go
  23. 51
      mongox/database/deleteone.go
  24. 23
      mongox/database/index.go
  25. 6
      mongox/database/index_test.go
  26. 71
      mongox/database/loadarray.go
  27. 57
      mongox/database/loadone.go
  28. 19
      mongox/database/loadstream.go
  29. 36
      mongox/database/saveone.go
  30. 44
      mongox/database/streamloader.go
  31. 52
      mongox/database/updateone.go
  32. 8
      mongox/errors.go
  33. 7
      mongox/mongox.go
  34. 4
      mongox/query/callbacks.go
  35. 58
      mongox/query/callbacks_test.go
  36. 44
      mongox/query/compose.go
  37. 128
      mongox/query/compose_test.go
  38. 9
      mongox/query/context.go
  39. 5
      mongox/query/limit.go
  40. 4
      mongox/query/preload.go
  41. 50
      mongox/query/query.go
  42. 5
      mongox/query/skip.go

@ -4,7 +4,7 @@ go 1.13
require (
github.com/modern-go/reflect2 v1.0.2
github.com/stretchr/testify v1.7.0
github.com/stretchr/testify v1.8.4
github.com/valyala/bytebufferpool v1.0.0
go.mongodb.org/mongo-driver v1.8.2
go.mongodb.org/mongo-driver v1.11.6
)

@ -1,8 +1,6 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
@ -16,50 +14,53 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.0.2 h1:akYIkZ28e6A96dkWNJQu3nmCzH3YfwMPQExUYDaRv7w=
github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs=
github.com/xdg-go/stringprep v1.0.2 h1:6iq84/ryjjeRmMJwxutI51F2GIPlP5BfTvXHeYjyhBc=
github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM=
github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E=
github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g=
github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs=
github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
go.mongodb.org/mongo-driver v1.8.2 h1:8ssUXufb90ujcIvR6MyE1SchaNj0SFxsakiZgxIyrMk=
go.mongodb.org/mongo-driver v1.8.2/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCuAROlKEPY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f h1:aZp0e2vLN4MToVqnjNEYEtrEA8RH8U8FN1CU7JgqsPU=
golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
go.mongodb.org/mongo-driver v1.11.6 h1:XM7G6PjiGAO5betLF13BIa5TlLUUE3uJ/2Ox3Lz1K+o=
go.mongodb.org/mongo-driver v1.11.6/go.mod h1:G9TgswdsWjX4tmDA5zfs2+6AEPpYJwqblyjsfuh8oXY=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

@ -29,18 +29,24 @@ func init() {
// NewEphemeral creates new mongo connection
func NewEphemeral(URI string) (db *EphemeralDatabase, err error) {
return NewEphemeralWithContext(context.Background(), URI)
}
func NewEphemeralWithContext(ctx context.Context, URI string) (db *EphemeralDatabase, err error) {
if URI == "" {
URI = defaultURI
}
name := primitive.NewObjectID().Hex()
opts := options.Client().ApplyURI(URI)
client, err := mongo.Connect(context.Background(), opts)
client, err := mongo.Connect(ctx, opts)
if err != nil {
return nil, err
}
db = &EphemeralDatabase{Database: database.NewDatabase(client, name)}
db = &EphemeralDatabase{Database: database.NewDatabase(ctx, client, name)}
return
return db, nil
}
// Close the connection and drop database

@ -0,0 +1,44 @@
package docbased
import (
"github.com/modern-go/reflect2"
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/mainnika/mongox-go-driver/v2/mongox"
)
var _ mongox.DocBased = (*Primary)(nil)
// Primary is a structure with object as an _id field
type Primary struct {
ID primitive.D `bson:"_id" json:"_id"`
}
// GetID returns an _id
func (p *Primary) GetID() (id primitive.D) {
return p.ID
}
// SetID sets an _id
func (p *Primary) SetID(id primitive.D) {
p.ID = id
}
// New creates a new Primary structure with a defined _id
func New(e primitive.E, ee ...primitive.E) Primary {
id := primitive.D{e}
if len(ee) > 0 {
id = append(id, ee...)
}
return Primary{ID: id}
}
func GetID(source mongox.DocBased) (id primitive.D, err error) {
id = source.GetID()
if !reflect2.IsNil(id) {
return id, nil
}
return nil, mongox.ErrUninitializedBase
}

@ -1,4 +1,4 @@
package jsonbased_test
package docbased_test
import (
"encoding/json"
@ -8,27 +8,25 @@ import (
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/mainnika/mongox-go-driver/v2/mongox-testing/database"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/jsonbased"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/docbased"
)
func Test_GetID(t *testing.T) {
type DocWithObject struct {
jsonbased.Primary `bson:",inline" json:",inline" collection:"1"`
docbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
doc := &DocWithObject{Primary: jsonbased.Primary{ID: primitive.D{{"1", "one"}, {"2", "two"}}}}
doc := &DocWithObject{Primary: docbased.New(primitive.E{"1", "one"}, primitive.E{"2", "two"})}
assert.Equal(t, primitive.D{{"1", "one"}, {"2", "two"}}, doc.GetID())
}
func Test_SetID(t *testing.T) {
type DocWithObject struct {
jsonbased.Primary `bson:",inline" json:",inline" collection:"1"`
docbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
doc := &DocWithObject{Primary: jsonbased.Primary{ID: primitive.D{{"1", "one"}, {"2", "two"}}}}
doc := &DocWithObject{Primary: docbased.New(primitive.E{"1", "one"}, primitive.E{"2", "two"})}
doc.SetID(primitive.D{{"3", "three"}, {"4", "you"}})
@ -37,9 +35,8 @@ func Test_SetID(t *testing.T) {
}
func Test_SaveLoad(t *testing.T) {
type DocWithObjectID struct {
jsonbased.Primary `bson:",inline" json:",inline" collection:"1"`
docbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
db, err := database.NewEphemeral("")
@ -47,9 +44,9 @@ func Test_SaveLoad(t *testing.T) {
t.Fatal(err)
}
defer db.Close()
defer func() { _ = db.Close() }()
doc1 := &DocWithObjectID{Primary: jsonbased.Primary{ID: primitive.D{{"1", "one"}, {"2", "two"}}}}
doc1 := &DocWithObjectID{Primary: docbased.New(primitive.E{"1", "one"}, primitive.E{"2", "two"})}
doc2 := &DocWithObjectID{}
err = db.SaveOne(doc1)
@ -67,12 +64,11 @@ func Test_SaveLoad(t *testing.T) {
}
func Test_Marshal(t *testing.T) {
type DocWithObjectID struct {
jsonbased.Primary `bson:",inline" json:",inline" collection:"1"`
docbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
doc := &DocWithObjectID{Primary: jsonbased.Primary{ID: primitive.D{{"1", "one"}, {"2", "two"}}}}
doc := &DocWithObjectID{Primary: docbased.New(primitive.E{"1", "one"}, primitive.E{"2", "two"})}
bytes, err := json.Marshal(doc)
assert.NoError(t, err)

@ -2,70 +2,26 @@ package base
import (
"fmt"
"github.com/modern-go/reflect2"
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/docbased"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/ifacebased"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/oidbased"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/stringbased"
"github.com/mainnika/mongox-go-driver/v2/mongox"
)
// GetID returns source document id
func GetID(source interface{}) (id interface{}) {
func GetID(source interface{}) (id interface{}, err error) {
switch doc := source.(type) {
case mongox.OIDBased:
return getObjectIDOrGenerate(doc)
return oidbased.GetID(doc)
case mongox.StringBased:
return getStringIDOrPanic(doc)
case mongox.JSONBased:
return getObjectOrPanic(doc)
return stringbased.GetID(doc)
case mongox.DocBased:
return docbased.GetID(doc)
case mongox.InterfaceBased:
return getInterfaceOrPanic(doc)
return ifacebased.GetID(doc)
default:
panic(fmt.Errorf("source contains malformed document, %v", source))
}
}
func getObjectIDOrGenerate(source mongox.OIDBased) (id primitive.ObjectID) {
id = source.GetID()
if id != primitive.NilObjectID {
return id
}
id = primitive.NewObjectID()
source.SetID(id)
return
}
func getStringIDOrPanic(source mongox.StringBased) (id string) {
id = source.GetID()
if id != "" {
return id
}
panic(fmt.Errorf("source contains malformed document, %v", source))
}
func getObjectOrPanic(source mongox.JSONBased) (id primitive.D) {
id = source.GetID()
if id != nil {
return id
return nil, fmt.Errorf("%w: unknown base type", mongox.ErrMalformedBase)
}
panic(fmt.Errorf("source contains malformed document, %v", source))
}
func getInterfaceOrPanic(source mongox.InterfaceBased) (id interface{}) {
id = source.GetID()
if !reflect2.IsNil(id) {
return id
}
panic(fmt.Errorf("source contains malformed document, %v", source))
}

@ -1,13 +1,14 @@
package base_test
import (
"github.com/mainnika/mongox-go-driver/v2/mongox/base/docbased"
"github.com/stretchr/testify/require"
"testing"
"github.com/stretchr/testify/assert"
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/mainnika/mongox-go-driver/v2/mongox/base"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/jsonbased"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/oidbased"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/stringbased"
)
@ -29,15 +30,24 @@ func TestGetID(t *testing.T) {
type DocWithObjectID struct {
oidbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
id, err := base.GetID(&DocWithObjectID{Primary: oidbased.Primary{ID: [12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2}}})
require.NoError(t, err)
assert.Equal(t, primitive.ObjectID([12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2}), id)
type DocWithObject struct {
jsonbased.Primary `bson:",inline" json:",inline" collection:"2"`
docbased.Primary `bson:",inline" json:",inline" collection:"2"`
}
id, err = base.GetID(&DocWithObject{Primary: docbased.Primary{ID: primitive.D{{"1", "2"}}}})
require.NoError(t, err)
assert.Equal(t, primitive.D{{"1", "2"}}, id)
type DocWithString struct {
stringbased.Primary `bson:",inline" json:",inline" collection:"3"`
}
id, err = base.GetID(&DocWithString{Primary: stringbased.Primary{ID: "foobar"}})
assert.Equal(t, "foobar", id)
assert.Equal(t, primitive.ObjectID([12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2}), base.GetID(&DocWithObjectID{Primary: oidbased.Primary{ID: [12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2}}}))
assert.Equal(t, primitive.D{{"1", "2"}}, base.GetID(&DocWithObject{Primary: jsonbased.Primary{ID: primitive.D{{"1", "2"}}}}))
assert.Equal(t, "foobar", base.GetID(&DocWithString{Primary: stringbased.Primary{ID: "foobar"}}))
assert.Equal(t, 420, base.GetID(&DocWithCustomInterface{ID: 420}))
id, err = base.GetID(&DocWithCustomInterface{ID: 420})
assert.NoError(t, err)
assert.Equal(t, 420, id)
}

@ -1,40 +0,0 @@
package base
import (
"reflect"
"github.com/mainnika/mongox-go-driver/v2/mongox/base/protection"
)
// GetProtection function finds protection field in the source document otherwise returns nil
func GetProtection(source interface{}) (key *protection.Key) {
v := reflect.ValueOf(source)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
el := v.Elem()
numField := el.NumField()
for i := 0; i < numField; i++ {
field := el.Field(i)
if !field.CanInterface() {
continue
}
switch field.Interface().(type) {
case *protection.Key:
key = field.Interface().(*protection.Key)
case protection.Key:
ptr := field.Addr()
key = ptr.Interface().(*protection.Key)
default:
continue
}
return
}
return
}

@ -0,0 +1,16 @@
package ifacebased
import (
"github.com/mainnika/mongox-go-driver/v2/mongox"
"github.com/modern-go/reflect2"
)
// GetID returns an _id from the source document
func GetID(source mongox.InterfaceBased) (id interface{}, err error) {
id = source.GetID()
if !reflect2.IsNil(id) {
return id, nil
}
return nil, mongox.ErrUninitializedBase
}

@ -1,24 +0,0 @@
package jsonbased
import (
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/mainnika/mongox-go-driver/v2/mongox"
)
var _ mongox.JSONBased = (*Primary)(nil)
// Primary is a structure with object as an _id field
type Primary struct {
ID primitive.D `bson:"_id" json:"_id"`
}
// GetID returns an _id
func (p *Primary) GetID() (id primitive.D) {
return p.ID
}
// SetID sets an _id
func (p *Primary) SetID(id primitive.D) {
p.ID = id
}

@ -22,3 +22,22 @@ func (p *Primary) GetID() (id primitive.ObjectID) {
func (p *Primary) SetID(id primitive.ObjectID) {
p.ID = id
}
// Generate creates a new Primary structure with a new objectId
func Generate() Primary {
return Primary{ID: primitive.NewObjectID()}
}
// New creates a new Primary structure with a defined objectId
func New(id primitive.ObjectID) Primary {
return Primary{ID: id}
}
func GetID(source mongox.OIDBased) (id primitive.ObjectID, err error) {
id = source.GetID()
if id != primitive.NilObjectID {
return id, nil
}
return primitive.NilObjectID, mongox.ErrUninitializedBase
}

@ -12,24 +12,22 @@ import (
)
func Test_GetID(t *testing.T) {
type DocWithObjectID struct {
oidbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
doc := &DocWithObjectID{Primary: oidbased.Primary{ID: [12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2}}}
doc := &DocWithObjectID{Primary: oidbased.New([12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2})}
assert.Equal(t, primitive.ObjectID([12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2}), doc.Primary.ID)
assert.Equal(t, primitive.ObjectID([12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2}), doc.GetID())
}
func Test_SetID(t *testing.T) {
type DocWithObjectID struct {
oidbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
doc := &DocWithObjectID{}
doc := &DocWithObjectID{Primary: oidbased.Generate()}
doc.SetID([12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2})
assert.Equal(t, primitive.ObjectID([12]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2}), doc.Primary.ID)
@ -37,7 +35,6 @@ func Test_SetID(t *testing.T) {
}
func Test_SaveLoad(t *testing.T) {
type DocWithObjectID struct {
oidbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
@ -47,10 +44,10 @@ func Test_SaveLoad(t *testing.T) {
t.Fatal(err)
}
defer db.Close()
defer func() { _ = db.Close() }()
doc1 := &DocWithObjectID{}
doc2 := &DocWithObjectID{}
doc1 := &DocWithObjectID{Primary: oidbased.Generate()}
doc2 := &DocWithObjectID{Primary: oidbased.Generate()}
err = db.SaveOne(doc1)
assert.NoError(t, err)
@ -67,13 +64,12 @@ func Test_SaveLoad(t *testing.T) {
}
func Test_Marshal(t *testing.T) {
type DocWithObjectID struct {
oidbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
id, _ := primitive.ObjectIDFromHex("feadbeeffeadbeeffeadbeef")
doc := &DocWithObjectID{Primary: oidbased.Primary{ID: id}}
doc := &DocWithObjectID{Primary: oidbased.New(id)}
bytes, err := json.Marshal(doc)
assert.NoError(t, err)

@ -1,6 +1,7 @@
package protection
import (
"reflect"
"time"
"github.com/modern-go/reflect2"
@ -13,9 +14,8 @@ type Key struct {
V int64 `bson:"_v" json:"_v"`
}
// PutToDocument extends the doc with protection key values
func (k *Key) PutToDocument(doc primitive.M) {
// Inject extends the doc with protection key values
func (k *Key) Inject(doc primitive.M) {
if reflect2.IsNil(doc) {
return
}
@ -34,3 +34,35 @@ func (k *Key) Restate() {
k.X = primitive.NewObjectID()
k.V = time.Now().Unix()
}
// Get finds protection field in the source document otherwise returns nil
func Get(source interface{}) (key *Key) {
v := reflect.ValueOf(source)
if v.Kind() != reflect.Ptr || v.IsNil() {
return nil
}
el := v.Elem()
numField := el.NumField()
for i := 0; i < numField; i++ {
field := el.Field(i)
if !field.CanInterface() {
continue
}
switch field.Interface().(type) {
case *Key:
key = field.Interface().(*Key)
case Key:
ptr := field.Addr()
key = ptr.Interface().(*Key)
default:
continue
}
return key
}
return nil
}

@ -0,0 +1,3 @@
package protection_test
// TODO:

@ -7,7 +7,6 @@ import (
// Reset function creates new zero object for the target pointer
func Reset(target interface{}) (created bool) {
type resetter interface {
Reset()
}

@ -20,3 +20,17 @@ func (p *Primary) GetID() (id string) {
func (p *Primary) SetID(id string) {
p.ID = id
}
// New creates a new Primary structure with a defined _id
func New(id string) Primary {
return Primary{ID: id}
}
func GetID(source mongox.StringBased) (id string, err error) {
id = source.GetID()
if id != "" {
return id, nil
}
return "", mongox.ErrUninitializedBase
}

@ -11,23 +11,21 @@ import (
)
func Test_GetID(t *testing.T) {
type DocWithString struct {
stringbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
doc := &DocWithString{Primary: stringbased.Primary{ID: "foobar"}}
doc := &DocWithString{Primary: stringbased.New("foobar")}
assert.Equal(t, "foobar", doc.GetID())
}
func Test_SetID(t *testing.T) {
type DocWithString struct {
stringbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
doc := &DocWithString{Primary: stringbased.Primary{ID: "foobar"}}
doc := &DocWithString{Primary: stringbased.New("foobar")}
doc.SetID("rockrockrock")
@ -36,7 +34,6 @@ func Test_SetID(t *testing.T) {
}
func Test_SaveLoad(t *testing.T) {
type DocWithObjectID struct {
stringbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
@ -46,9 +43,9 @@ func Test_SaveLoad(t *testing.T) {
t.Fatal(err)
}
defer db.Close()
defer func() { _ = db.Close() }()
doc1 := &DocWithObjectID{Primary: stringbased.Primary{ID: "foobar"}}
doc1 := &DocWithObjectID{Primary: stringbased.New("foobar")}
doc2 := &DocWithObjectID{}
err = db.SaveOne(doc1)
@ -66,12 +63,11 @@ func Test_SaveLoad(t *testing.T) {
}
func Test_Marshal(t *testing.T) {
type DocWithObjectID struct {
stringbased.Primary `bson:",inline" json:",inline" collection:"1"`
}
doc := &DocWithObjectID{Primary: stringbased.Primary{ID: "foobar"}}
doc := &DocWithObjectID{Primary: stringbased.New("foobar")}
bytes, err := json.Marshal(doc)
assert.NoError(t, err)

@ -0,0 +1,23 @@
package database
import (
"context"
)
type ctxDatabaseKey struct{}
// GetFromContext function extracts the request data from context
func GetFromContext(ctx context.Context) (q *Database, ok bool) {
q, ok = ctx.Value(ctxDatabaseKey{}).(*Database)
if !ok {
return nil, false
}
return q, true
}
// WithContext creates the new context with a database attached
func WithContext(ctx context.Context, q *Database) (withQuery context.Context) {
db := NewDatabase(ctx, q.Client(), q.Name())
return context.WithValue(ctx, ctxDatabaseKey{}, db)
}

@ -9,22 +9,29 @@ import (
// Count function counts documents in the database by query
// target is used only to get collection by tag so it'd be better to use nil ptr here
func (d *Database) Count(target interface{}, filters ...interface{}) (result int64, err error) {
composed, err := query.Compose(filters...)
if err != nil {
return
return -1, err
}
collection := d.GetCollectionOf(target)
collection, err := d.GetCollectionOf(target)
if err != nil {
return -1, err
}
ctx := query.WithContext(d.Context(), composed)
m := composed.M()
opts := options.Count()
opts.Limit = composed.Limiter()
opts.Skip = composed.Skipper()
result, err = collection.CountDocuments(ctx, composed.M(), opts)
defer func() { _ = composed.OnClose().Invoke(ctx, target) }()
_ = composed.OnClose().Invoke(ctx, target)
result, err = collection.CountDocuments(ctx, m, opts)
if err != nil {
return -1, err
}
return
return result, nil
}

@ -0,0 +1,188 @@
package database
import (
"fmt"
"reflect"
"strconv"
"strings"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/mainnika/mongox-go-driver/v2/mongox"
"github.com/mainnika/mongox-go-driver/v2/mongox/query"
)
func (d *Database) createCursor(target interface{}, composed *query.Query) (cursor *mongox.Cursor, err error) {
_, hasPreloader := composed.Preloader()
if hasPreloader {
return d.createAggregateCursor(target, composed)
}
return d.createSimpleCursor(target, composed)
}
func (d *Database) createSimpleCursor(target interface{}, composed *query.Query) (cursor *mongox.Cursor, err error) {
collection, err := d.GetCollectionOf(target)
if err != nil {
return nil, err
}
opts := options.Find()
opts.Sort = composed.Sorter()
opts.Limit = composed.Limiter()
opts.Skip = composed.Skipper()
ctx := d.Context()
m := composed.M()
return collection.Find(ctx, m, opts)
}
func (d *Database) createAggregateCursor(target interface{}, composed *query.Query) (cursor *mongox.Cursor, err error) {
collection, err := d.GetCollectionOf(target)
if err != nil {
return nil, err
}
pipeline := primitive.A{}
if !composed.Empty() {
pipeline = append(pipeline, primitive.M{"$match": composed.M()})
}
if composed.Sorter() != nil {
pipeline = append(pipeline, primitive.M{"$sort": composed.Sorter()})
}
if composed.Skipper() != nil {
pipeline = append(pipeline, primitive.M{"$skip": *composed.Skipper()})
}
if composed.Limiter() != nil {
pipeline = append(pipeline, primitive.M{"$limit": *composed.Limiter()})
}
el := reflect.ValueOf(target)
elType := el.Type()
if elType.Kind() == reflect.Ptr {
elType = elType.Elem()
}
numField := elType.NumField()
preloads, _ := composed.Preloader()
for i := 0; i < numField; i++ {
field := elType.Field(i)
tag := field.Tag
preloadTag, ok := tag.Lookup("preload")
if !ok {
continue
}
jsonTag, _ := tag.Lookup("json")
if jsonTag == "-" {
return nil, fmt.Errorf("%w: private field is not preloadable", mongox.ErrMalformedBase)
}
jsonData := strings.SplitN(jsonTag, ",", 2)
jsonName := field.Name
if len(jsonData) > 0 {
jsonName = strings.TrimSpace(jsonData[0])
}
preloadData := strings.Split(preloadTag, ",")
if len(preloadData) == 0 {
continue
}
if len(preloadData) == 1 {
return nil, fmt.Errorf("%w: foreign field is not specified", mongox.ErrMalformedBase)
}
foreignField := strings.TrimSpace(preloadData[1])
if len(foreignField) == 0 {
return nil, fmt.Errorf("%w: foreign field is empty", mongox.ErrMalformedBase)
}
localField := strings.TrimSpace(preloadData[0])
if len(localField) == 0 {
localField = "_id"
}
preloadLimiter := 100
preloadReversed := false
if len(preloadData) > 2 {
stringLimit := strings.TrimSpace(preloadData[2])
intLimit := preloadLimiter
preloadReversed = strings.HasPrefix(stringLimit, "-")
if preloadReversed {
stringLimit = stringLimit[1:]
}
intLimit, err = strconv.Atoi(stringLimit)
if err == nil {
preloadLimiter = intLimit
} else {
return nil, fmt.Errorf("%w: preload limit should be an integer", mongox.ErrMalformedBase)
}
}
for _, preload := range preloads {
if preload != jsonName {
continue
}
field := elType.Field(i)
fieldType := field.Type
isSlice := fieldType.Kind() == reflect.Slice
if isSlice {
fieldType = fieldType.Elem()
}
isPtr := fieldType.Kind() != reflect.Ptr
if isPtr {
return nil, fmt.Errorf("%w: preload field should have ptr type", mongox.ErrMalformedBase)
}
lookupCollection, err := d.GetCollectionOf(reflect.Zero(fieldType).Interface())
if err != nil {
return nil, err
}
lookupVars := primitive.M{"selector": "$" + localField}
lookupPipeline := primitive.A{
primitive.M{"$match": primitive.M{"$expr": primitive.M{"$eq": primitive.A{"$" + foreignField, "$$selector"}}}},
}
if preloadReversed {
lookupPipeline = append(lookupPipeline, primitive.M{"$sort": primitive.M{"_id": -1}})
}
if isSlice && preloadLimiter > 0 {
lookupPipeline = append(lookupPipeline, primitive.M{"$limit": preloadLimiter})
} else if !isSlice {
lookupPipeline = append(lookupPipeline, primitive.M{"$limit": 1})
}
pipeline = append(pipeline, primitive.M{
"$lookup": primitive.M{
"from": lookupCollection.Name(),
"let": lookupVars,
"pipeline": lookupPipeline,
"as": jsonName,
},
})
if isSlice {
continue
}
pipeline = append(pipeline, primitive.M{
"$unwind": primitive.M{
"preserveNullAndEmptyArrays": true,
"path": "$" + jsonName,
},
})
}
}
ctx := d.Context()
opts := options.Aggregate()
return collection.Aggregate(ctx, pipeline, opts)
}

@ -2,34 +2,27 @@ package database
import (
"context"
"fmt"
"reflect"
"strconv"
"strings"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/mainnika/mongox-go-driver/v2/mongox"
"github.com/mainnika/mongox-go-driver/v2/mongox/query"
)
// Database handler
type Database struct {
client *mongox.Client
dbname string
name string
ctx context.Context
}
// NewDatabase function creates new database instance with mongo client and empty context
func NewDatabase(client *mongox.Client, dbname string) (db mongox.Database) {
func NewDatabase(ctx context.Context, client *mongox.Client, name string) (db mongox.Database) {
db = &Database{
client: client,
dbname: dbname,
name: name,
ctx: ctx,
}
return
return db
}
// Client function returns a mongo client
@ -37,213 +30,42 @@ func (d *Database) Client() (client *mongox.Client) {
return d.client
}
// Context function returns a context
func (d *Database) Context() (ctx context.Context) {
ctx = d.ctx
if ctx == nil {
ctx = context.Background()
}
return
}
// Name function returns a database name
func (d *Database) Name() (name string) {
return d.dbname
return d.name
}
// New function creates new database context with same client
func (d *Database) New(ctx context.Context) (db mongox.Database) {
// Context function returns a context
func (d *Database) Context() (ctx context.Context) {
ctx = d.ctx
if ctx == nil {
ctx = context.Background()
}
db = &Database{
client: d.client,
dbname: d.dbname,
ctx: ctx,
}
return
return ctx
}
// GetCollectionOf returns the collection object by the «collection» tag of the given document;
// the «collection» tag should exists, e.g.:
// type Foobar struct {
// base.ObjectID `bson:",inline" json:",inline" collection:"foobars"`
// ...
// Will panic if there is no «collection» tag
func (d *Database) GetCollectionOf(document interface{}) (collection *mongox.Collection) {
//
// example:
// type Foobar struct {
// base.ObjectID `bson:",inline" json:",inline" collection:"foobars"`
// ...
func (d *Database) GetCollectionOf(document interface{}) (collection *mongox.Collection, err error) {
el := reflect.TypeOf(document).Elem()
numField := el.NumField()
databaseName := d.name
for i := 0; i < numField; i++ {
field := el.Field(i)
tag := field.Tag
found, ok := tag.Lookup("collection")
if !ok {
collectionName, found := tag.Lookup("collection")
if !found {
continue
}
return d.client.Database(d.dbname).Collection(found)
}
panic(fmt.Errorf("document %v does not have a collection tag", document))
}
func (d *Database) createSimpleLoad(target interface{}, composed *query.Query) (cursor *mongox.Cursor, err error) {
collection := d.GetCollectionOf(target)
opts := options.Find()
opts.Sort = composed.Sorter()
opts.Limit = composed.Limiter()
opts.Skip = composed.Skipper()
return collection.Find(d.Context(), composed.M(), opts)
}
func (d *Database) createAggregateLoad(target interface{}, composed *query.Query) (cursor *mongox.Cursor, err error) {
collection := d.GetCollectionOf(target)
opts := options.Aggregate()
pipeline := primitive.A{}
if !composed.Empty() {
pipeline = append(pipeline, primitive.M{"$match": composed.M()})
}
if composed.Sorter() != nil {
pipeline = append(pipeline, primitive.M{"$sort": composed.Sorter()})
}
if composed.Skipper() != nil {
pipeline = append(pipeline, primitive.M{"$skip": *composed.Skipper()})
}
if composed.Limiter() != nil {
pipeline = append(pipeline, primitive.M{"$limit": *composed.Limiter()})
}
el := reflect.ValueOf(target)
elType := el.Type()
if elType.Kind() == reflect.Ptr {
elType = elType.Elem()
}
numField := elType.NumField()
preloads, _ := composed.Preloader()
for i := 0; i < numField; i++ {
field := elType.Field(i)
tag := field.Tag
preloadTag, ok := tag.Lookup("preload")
if !ok {
continue
}
jsonTag, _ := tag.Lookup("json")
if jsonTag == "-" {
panic(fmt.Errorf("preload private field is impossible"))
}
jsonData := strings.SplitN(jsonTag, ",", 2)
jsonName := field.Name
if len(jsonData) > 0 {
jsonName = strings.TrimSpace(jsonData[0])
}
preloadData := strings.Split(preloadTag, ",")
if len(preloadData) == 0 {
continue
}
if len(preloadData) == 1 {
panic(fmt.Errorf("there is no foreign field"))
}
localField := strings.TrimSpace(preloadData[0])
if len(localField) == 0 {
localField = "_id"
}
foreignField := strings.TrimSpace(preloadData[1])
if len(foreignField) == 0 {
panic(fmt.Errorf("there is no foreign field"))
}
preloadLimiter := 100
preloadReversed := false
if len(preloadData) > 2 {
stringLimit := strings.TrimSpace(preloadData[2])
intLimit := preloadLimiter
preloadReversed = strings.HasPrefix(stringLimit, "-")
if preloadReversed {
stringLimit = stringLimit[1:]
}
intLimit, err = strconv.Atoi(stringLimit)
if err == nil {
preloadLimiter = intLimit
}
}
for _, preload := range preloads {
if preload != jsonName {
continue
}
field := elType.Field(i)
fieldType := field.Type
isSlice := fieldType.Kind() == reflect.Slice
if isSlice {
fieldType = fieldType.Elem()
}
isPtr := fieldType.Kind() != reflect.Ptr
if isPtr {
panic(fmt.Errorf("preload field should have ptr type"))
}
lookupCollection := d.GetCollectionOf(reflect.Zero(fieldType).Interface())
lookupVars := primitive.M{"selector": "$" + localField}
lookupPipeline := primitive.A{
primitive.M{"$match": primitive.M{"$expr": primitive.M{"$eq": primitive.A{"$" + foreignField, "$$selector"}}}},
}
if preloadReversed {
lookupPipeline = append(lookupPipeline, primitive.M{"$sort": primitive.M{"_id": -1}})
}
if isSlice && preloadLimiter > 0 {
lookupPipeline = append(lookupPipeline, primitive.M{"$limit": preloadLimiter})
} else if !isSlice {
lookupPipeline = append(lookupPipeline, primitive.M{"$limit": 1})
}
pipeline = append(pipeline, primitive.M{
"$lookup": primitive.M{
"from": lookupCollection.Name(),
"let": lookupVars,
"pipeline": lookupPipeline,
"as": jsonName,
},
})
if isSlice {
continue
}
pipeline = append(pipeline, primitive.M{
"$unwind": primitive.M{
"preserveNullAndEmptyArrays": true,
"path": "$" + jsonName,
},
})
}
return d.client.Database(databaseName).Collection(collectionName), nil
}
return collection.Aggregate(d.Context(), pipeline, opts)
return nil, mongox.ErrNoCollection
}

@ -13,7 +13,6 @@ import (
// DeleteArray removes documents list from a database by their ids
func (d *Database) DeleteArray(target interface{}, filters ...interface{}) (err error) {
targetV := reflect.ValueOf(target)
targetT := targetV.Type()
@ -36,42 +35,43 @@ func (d *Database) DeleteArray(target interface{}, filters ...interface{}) (err
zeroElem := reflect.Zero(targetSliceElemT)
targetLen := targetSliceV.Len()
composed, err := query.Compose(filters...)
collection, err := d.GetCollectionOf(zeroElem.Interface())
if err != nil {
return
return err
}
collection := d.GetCollectionOf(zeroElem.Interface())
ids := primitive.A{}
ctx := query.WithContext(d.Context(), composed)
for i := 0; i < targetLen; i++ {
elem := targetSliceV.Index(i)
ids = append(ids, base.GetID(elem.Interface()))
composed, err := query.Compose(filters...)
if err != nil {
return err
}
defer func() {
invokerr := composed.OnClose().Invoke(ctx, target)
if err == nil {
err = invokerr
}
return
}()
if targetLen > 0 {
var ids primitive.A
for i := 0; i < targetLen; i++ {
elem := targetSliceV.Index(i)
elemID, err := base.GetID(elem.Interface())
if err != nil {
return err
}
if len(ids) == 0 {
return fmt.Errorf("can't delete zero elements")
ids = append(ids, elemID)
}
composed.And(primitive.M{"_id": primitive.M{"$in": ids}})
}
composed.And(primitive.M{"_id": primitive.M{"$in": ids}})
ctx := query.WithContext(d.Context(), composed)
m := composed.M()
opts := options.Delete()
defer func() { _ = composed.OnClose().Invoke(ctx, target) }()
result, err := collection.DeleteMany(ctx, composed.M(), options.Delete())
result, err := collection.DeleteMany(ctx, m, opts)
if err != nil {
return
return fmt.Errorf("while deleting array: %w", err)
}
if result.DeletedCount != int64(targetLen) {
err = fmt.Errorf("can't verify delete result: removed count mismatch %d != %d", result.DeletedCount, targetLen)
return fmt.Errorf("deleted count mismatch %d != %d", result.DeletedCount, targetLen)
}