Use named returns for the code style consistency

v2
Nikita Tokarchuk 4 years ago
parent 9cf3551c20
commit 72e74a65b6
  1. 2
      mongox-testing/database/ephemeral.go
  2. 12
      mongox/base/getprotection.go
  3. 2
      mongox/base/jsonbased/id.go
  4. 2
      mongox/base/oidbased/id.go
  5. 2
      mongox/base/stringbased/id.go
  6. 6
      mongox/database/count.go
  7. 23
      mongox/database/database.go
  8. 6
      mongox/database/deletearray.go
  9. 6
      mongox/database/deleteone.go
  10. 12
      mongox/database/index.go
  11. 9
      mongox/database/loadarray.go
  12. 3
      mongox/database/loadone.go
  13. 10
      mongox/database/loadstream.go
  14. 2
      mongox/database/saveone.go
  15. 47
      mongox/database/streamloader.go
  16. 46
      mongox/mongox.go
  17. 24
      mongox/query/compose.go
  18. 14
      mongox/query/limit.go
  19. 4
      mongox/query/preload.go
  20. 29
      mongox/query/query.go
  21. 14
      mongox/query/skip.go
  22. 4
      mongox/query/sort.go
  23. 8
      mongox/utils/isnil.go

@ -30,6 +30,6 @@ func NewEphemeral(URI string) (db *EphemeralDatabase, err error) {
}
// Close the connection and drop database
func (e *EphemeralDatabase) Close() error {
func (e *EphemeralDatabase) Close() (err error) {
return e.Client().Database(e.Name()).Drop(e.Context())
}

@ -7,11 +7,11 @@ import (
)
// GetProtection function finds protection field in the source document otherwise returns nil
func GetProtection(source interface{}) *protection.Key {
func GetProtection(source interface{}) (key *protection.Key) {
v := reflect.ValueOf(source)
if v.Kind() != reflect.Ptr || v.IsNil() {
return nil
return
}
el := v.Elem()
@ -25,14 +25,16 @@ func GetProtection(source interface{}) *protection.Key {
switch field.Interface().(type) {
case *protection.Key:
return field.Interface().(*protection.Key)
key = field.Interface().(*protection.Key)
case protection.Key:
ptr := field.Addr()
return ptr.Interface().(*protection.Key)
key = ptr.Interface().(*protection.Key)
default:
continue
}
return
}
return nil
return
}

@ -14,7 +14,7 @@ type Primary struct {
}
// GetID returns an _id
func (p *Primary) GetID() primitive.D {
func (p *Primary) GetID() (id primitive.D) {
return p.ID
}

@ -14,7 +14,7 @@ type Primary struct {
}
// GetID returns an _id
func (p *Primary) GetID() primitive.ObjectID {
func (p *Primary) GetID() (id primitive.ObjectID) {
return p.ID
}

@ -12,7 +12,7 @@ type Primary struct {
}
// GetID returns an _id
func (p *Primary) GetID() string {
func (p *Primary) GetID() (id string) {
return p.ID
}

@ -11,7 +11,7 @@ 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{}) (int64, error) {
func (d *Database) Count(target interface{}, filters ...interface{}) (result int64, err error) {
collection := d.GetCollectionOf(target)
opts := options.Count()
@ -20,7 +20,7 @@ func (d *Database) Count(target interface{}, filters ...interface{}) (int64, err
opts.Limit = composed.Limiter()
opts.Skip = composed.Skipper()
result, err := collection.CountDocuments(d.Context(), composed.M(), opts)
result, err = collection.CountDocuments(d.Context(), composed.M(), opts)
if err == mongox.ErrNoDocuments {
return 0, err
}
@ -28,5 +28,5 @@ func (d *Database) Count(target interface{}, filters ...interface{}) (int64, err
return 0, fmt.Errorf("can't decode desult: %w", err)
}
return result, nil
return
}

@ -22,17 +22,18 @@ type Database struct {
}
// NewDatabase function creates new database instance with mongo client and empty context
func NewDatabase(client *mongox.Client, dbname string) mongox.Database {
func NewDatabase(client *mongox.Client, dbname string) (db mongox.Database) {
db := &Database{}
db.client = client
db.dbname = dbname
db = &Database{
client: client,
dbname: dbname,
}
return db
return
}
// Client function returns a mongo client
func (d *Database) Client() *mongox.Client {
func (d *Database) Client() (client *mongox.Client) {
return d.client
}
@ -48,22 +49,24 @@ func (d *Database) Context() (ctx context.Context) {
}
// Name function returns a database name
func (d *Database) Name() string {
func (d *Database) Name() (name string) {
return d.dbname
}
// New function creates new database context with same client
func (d *Database) New(ctx context.Context) mongox.Database {
func (d *Database) New(ctx context.Context) (db mongox.Database) {
if ctx == nil {
ctx = context.Background()
}
return &Database{
db = &Database{
client: d.client,
dbname: d.dbname,
ctx: ctx,
}
return
}
// GetCollectionOf returns the collection object by the «collection» tag of the given document;
@ -72,7 +75,7 @@ func (d *Database) New(ctx context.Context) mongox.Database {
// base.ObjectID `bson:",inline" json:",inline" collection:"foobars"`
// ...
// Will panic if there is no «collection» tag
func (d *Database) GetCollectionOf(document interface{}) *mongox.Collection {
func (d *Database) GetCollectionOf(document interface{}) (collection *mongox.Collection) {
el := reflect.TypeOf(document).Elem()
numField := el.NumField()

@ -11,7 +11,7 @@ import (
)
// DeleteArray removes documents list from a database by their ids
func (d *Database) DeleteArray(target interface{}) error {
func (d *Database) DeleteArray(target interface{}) (err error) {
targetV := reflect.ValueOf(target)
targetT := targetV.Type()
@ -52,8 +52,8 @@ func (d *Database) DeleteArray(target interface{}) error {
return fmt.Errorf("can't create find and delete result: %w", err)
}
if result.DeletedCount != int64(targetLen) {
return fmt.Errorf("can't verify delete result: removed count mismatch %d != %d", result.DeletedCount, targetLen)
err = fmt.Errorf("can't verify delete result: removed count mismatch %d != %d", result.DeletedCount, targetLen)
}
return nil
return
}

@ -14,7 +14,7 @@ import (
)
// DeleteOne removes a document from a database and then returns it into target
func (d *Database) DeleteOne(target interface{}, filters ...interface{}) error {
func (d *Database) DeleteOne(target interface{}, filters ...interface{}) (err error) {
collection := d.GetCollectionOf(target)
opts := &options.FindOneAndDeleteOptions{}
@ -38,7 +38,7 @@ func (d *Database) DeleteOne(target interface{}, filters ...interface{}) error {
return fmt.Errorf("can't create find one and delete result: %w", result.Err())
}
err := result.Decode(target)
err = result.Decode(target)
if err == mongox.ErrNoDocuments {
return err
}
@ -46,5 +46,5 @@ func (d *Database) DeleteOne(target interface{}, filters ...interface{}) error {
return fmt.Errorf("can't decode result: %w", err)
}
return nil
return
}

@ -21,7 +21,7 @@ import (
// `index:"-,+foo,+-bar,unique,allowNull"` -- https://docs.mongodb.com/manual/core/index-partial
// `index:"-,unique,allowNull,expireAfter=86400"` -- https://docs.mongodb.com/manual/core/index-ttl
// `index:"-,unique,allowNull,expireAfter={{.Expire}}"` -- evaluate index as a golang template with `cfg` arguments
func (d *Database) IndexEnsure(cfg interface{}, document interface{}) error {
func (d *Database) IndexEnsure(cfg interface{}, document interface{}) (err error) {
el := reflect.ValueOf(document).Elem().Type()
numField := el.NumField()
@ -41,8 +41,10 @@ func (d *Database) IndexEnsure(cfg interface{}, document interface{}) error {
return fmt.Errorf("bson tag is not defined for field:%v document:%v", field, document)
}
tmpBuffer := &bytes.Buffer{}
tpl, err := template.New("").Parse(indexTag)
var tmpBuffer = &bytes.Buffer{}
var tpl *template.Template
tpl, err = template.New("").Parse(indexTag)
if err != nil {
panic(fmt.Errorf("invalid prop template, %v", indexTag))
}
@ -126,9 +128,9 @@ func (d *Database) IndexEnsure(cfg interface{}, document interface{}) error {
_, err = documents.Indexes().CreateOne(d.Context(), mongo.IndexModel{Keys: index, Options: opts})
if err != nil {
return err
return
}
}
return nil
return
}

@ -10,7 +10,7 @@ import (
)
// LoadArray loads an array of documents from the database by query
func (d *Database) LoadArray(target interface{}, filters ...interface{}) error {
func (d *Database) LoadArray(target interface{}, filters ...interface{}) (err error) {
targetV := reflect.ValueOf(target)
targetT := targetV.Type()
@ -36,7 +36,7 @@ func (d *Database) LoadArray(target interface{}, filters ...interface{}) error {
hasPreloader, _ := composed.Preloader()
var result *mongox.Cursor
var err error
var i int
if hasPreloader {
result, err = d.createAggregateLoad(zeroElem.Interface(), composed)
@ -44,11 +44,10 @@ func (d *Database) LoadArray(target interface{}, filters ...interface{}) error {
result, err = d.createSimpleLoad(zeroElem.Interface(), composed)
}
if err != nil {
return fmt.Errorf("can't create find result: %w", err)
err = fmt.Errorf("can't create find result: %w", err)
return
}
var i int
for i = 0; result.Next(d.Context()); {
if targetSliceV.Len() == i {
elem := reflect.New(targetSliceElemT.Elem())

@ -9,13 +9,12 @@ import (
)
// LoadOne function loads a first single target document by a query
func (d *Database) LoadOne(target interface{}, filters ...interface{}) error {
func (d *Database) LoadOne(target interface{}, filters ...interface{}) (err error) {
composed := query.Compose(append(filters, query.Limit(1))...)
hasPreloader, _ := composed.Preloader()
var result *mongox.Cursor
var err error
if hasPreloader {
result, err = d.createAggregateLoad(target, composed)

@ -8,10 +8,9 @@ import (
)
// LoadStream function loads documents one by one into a target channel
func (d *Database) LoadStream(target interface{}, filters ...interface{}) (mongox.StreamLoader, error) {
func (d *Database) LoadStream(target interface{}, filters ...interface{}) (loader mongox.StreamLoader, err error) {
var cursor *mongox.Cursor
var err error
composed := query.Compose(filters...)
hasPreloader, _ := composed.Preloader()
@ -22,10 +21,11 @@ func (d *Database) LoadStream(target interface{}, filters ...interface{}) (mongo
cursor, err = d.createSimpleLoad(target, composed)
}
if err != nil {
return nil, fmt.Errorf("can't create find result: %w", err)
err = fmt.Errorf("can't create find result: %w", err)
return
}
l := &StreamLoader{cur: cursor, ctx: d.Context(), target: target}
loader = &StreamLoader{cur: cursor, ctx: d.Context(), target: target}
return l, nil
return
}

@ -12,7 +12,7 @@ import (
)
// SaveOne saves a single source document to the database
func (d *Database) SaveOne(source interface{}) error {
func (d *Database) SaveOne(source interface{}) (err error) {
collection := d.GetCollectionOf(source)
opts := options.FindOneAndReplace()

@ -2,7 +2,6 @@ package database
import (
"context"
"fmt"
"github.com/mainnika/mongox-go-driver/v2/mongox"
"github.com/mainnika/mongox-go-driver/v2/mongox/base"
@ -16,64 +15,56 @@ type StreamLoader struct {
}
// DecodeNext loads next documents to a target or returns an error
func (l *StreamLoader) DecodeNext() error {
func (l *StreamLoader) DecodeNext() (err error) {
hasNext := l.cur.Next(l.ctx)
if l.cur.Err() != nil {
return l.cur.Err()
}
if !hasNext {
return mongox.ErrNoDocuments
err = l.Next()
if err != nil {
return
}
base.Reset(l.target)
err := l.cur.Decode(l.target)
err = l.Decode()
if err != nil {
return fmt.Errorf("can't decode desult: %w", err)
return
}
return nil
return
}
// Decode function decodes the current cursor document into the target
func (l *StreamLoader) Decode() error {
func (l *StreamLoader) Decode() (err error) {
base.Reset(l.target)
err := l.cur.Decode(l.target)
if err != nil {
return fmt.Errorf("can't decode desult: %w", err)
}
err = l.cur.Decode(l.target)
return nil
return
}
// Next loads next documents but doesn't perform decoding
func (l *StreamLoader) Next() error {
func (l *StreamLoader) Next() (err error) {
hasNext := l.cur.Next(l.ctx)
err = l.cur.Err()
if l.cur.Err() != nil {
return l.cur.Err()
if err != nil {
return
}
if !hasNext {
return mongox.ErrNoDocuments
err = mongox.ErrNoDocuments
}
return nil
return
}
func (l *StreamLoader) Cursor() *mongox.Cursor {
func (l *StreamLoader) Cursor() (cursor *mongox.Cursor) {
return l.cur
}
// Close cursor
func (l *StreamLoader) Close() error {
func (l *StreamLoader) Close() (err error) {
return l.cur.Close(l.ctx)
}
func (l *StreamLoader) Err() error {
func (l *StreamLoader) Err() (err error) {
return l.cur.Err()
}

@ -16,51 +16,51 @@ type (
// Database is the mongox database interface
type Database interface {
Client() *Client
Context() context.Context
Name() string
New(ctx context.Context) Database
GetCollectionOf(document interface{}) *Collection
Count(target interface{}, filters ...interface{}) (int64, error)
DeleteArray(target interface{}) error
DeleteOne(target interface{}, filters ...interface{}) error
LoadArray(target interface{}, filters ...interface{}) error
LoadOne(target interface{}, filters ...interface{}) error
LoadStream(target interface{}, filters ...interface{}) (StreamLoader, error)
SaveOne(source interface{}) error
IndexEnsure(cfg interface{}, document interface{}) error
Client() (client *Client)
Context() (context context.Context)
Name() (name string)
New(ctx context.Context) (db Database)
GetCollectionOf(document interface{}) (collection *Collection)
Count(target interface{}, filters ...interface{}) (count int64, err error)
DeleteArray(target interface{}) (err error)
DeleteOne(target interface{}, filters ...interface{}) (err error)
LoadArray(target interface{}, filters ...interface{}) (err error)
LoadOne(target interface{}, filters ...interface{}) (err error)
LoadStream(target interface{}, filters ...interface{}) (loader StreamLoader, err error)
SaveOne(source interface{}) (err error)
IndexEnsure(cfg interface{}, document interface{}) (err error)
}
// StreamLoader is a interface to control database cursor
type StreamLoader interface {
Cursor() *Cursor
DecodeNext() error
Decode() error
Next() error
Close() error
Err() error
Cursor() (cursor *Cursor)
DecodeNext() (err error)
Decode() (err error)
Next() (err error)
Close() (err error)
Err() (err error)
}
// OIDBased is an interface for documents that have objectId type for the _id field
type OIDBased interface {
GetID() primitive.ObjectID
GetID() (id primitive.ObjectID)
SetID(id primitive.ObjectID)
}
// StringBased is an interface for documents that have string type for the _id field
type StringBased interface {
GetID() string
GetID() (id string)
SetID(id string)
}
// JSONBased is an interface for documents that have object type for the _id field
type JSONBased interface {
GetID() primitive.D
GetID() (id primitive.D)
SetID(id primitive.D)
}
// InterfaceBased is an interface for documents that have custom declated type for the _id field
type InterfaceBased interface {
GetID() interface{}
GetID() (id interface{})
SetID(id interface{})
}

@ -11,27 +11,27 @@ import (
)
// Compose is a function to compose filters into a single query
func Compose(filters ...interface{}) *Query {
func Compose(filters ...interface{}) (query *Query) {
q := &Query{}
query = &Query{}
for _, f := range filters {
if !Push(q, f) {
if !Push(query, f) {
panic(fmt.Errorf("unknown filter %v", f))
}
}
return q
return
}
// Push applies single filter to a query
func Push(q *Query, f interface{}) bool {
func Push(q *Query, f interface{}) (ok bool) {
if utils.IsNil(f) {
return true
}
ok := false
ok = false
ok = ok || applyBson(q, f)
ok = ok || applyLimit(q, f)
ok = ok || applySort(q, f)
@ -43,7 +43,7 @@ func Push(q *Query, f interface{}) bool {
}
// applyBson is a fallback for a custom bson.M
func applyBson(q *Query, f interface{}) bool {
func applyBson(q *Query, f interface{}) (ok bool) {
if f, ok := f.(bson.M); ok {
q.And(f)
@ -54,7 +54,7 @@ func applyBson(q *Query, f interface{}) bool {
}
// applyLimits extends query with a limiter
func applyLimit(q *Query, f interface{}) bool {
func applyLimit(q *Query, f interface{}) (ok bool) {
if f, ok := f.(Limiter); ok {
q.limiter = f
@ -65,7 +65,7 @@ func applyLimit(q *Query, f interface{}) bool {
}
// applySort extends query with a sort rule
func applySort(q *Query, f interface{}) bool {
func applySort(q *Query, f interface{}) (ok bool) {
if f, ok := f.(Sorter); ok {
q.sorter = f
@ -76,7 +76,7 @@ func applySort(q *Query, f interface{}) bool {
}
// applySkip extends query with a skip number
func applySkip(q *Query, f interface{}) bool {
func applySkip(q *Query, f interface{}) (ok bool) {
if f, ok := f.(Skipper); ok {
q.skipper = f
@ -86,7 +86,7 @@ func applySkip(q *Query, f interface{}) bool {
return false
}
func applyProtection(q *Query, f interface{}) bool {
func applyProtection(q *Query, f interface{}) (ok bool) {
var x *primitive.ObjectID
var v *int64
@ -114,7 +114,7 @@ func applyProtection(q *Query, f interface{}) bool {
return true
}
func applyPreloader(q *Query, f interface{}) bool {
func applyPreloader(q *Query, f interface{}) (ok bool) {
if f, ok := f.(Preloader); ok {
q.preloader = f

@ -2,7 +2,7 @@ package query
// Limiter is a filter to limit the result
type Limiter interface {
Limit() *int64
Limit() (limit *int64)
}
// Limit is a simple implementation of the Limiter filter
@ -11,12 +11,14 @@ type Limit int64
var _ Limiter = Limit(0)
// Limit returns a limit
func (l Limit) Limit() *int64 {
func (l Limit) Limit() (limit *int64) {
lim := int64(l)
if lim <= 0 {
return nil
if l <= 0 {
return
}
return &lim
limit = new(int64)
*limit = int64(l)
return
}

@ -2,7 +2,7 @@ package query
// Preloader is a filter to skip the result
type Preloader interface {
Preload() []string
Preload() (preloads []string)
}
// Preload is a simple implementation of the Skipper filter
@ -11,6 +11,6 @@ type Preload []string
var _ Preloader = Preload{}
// Preload returns a preload list
func (l Preload) Preload() []string {
func (l Preload) Preload() (preloads []string) {
return l
}

@ -14,7 +14,7 @@ type Query struct {
}
// And function pushes the elem query to the $and array of the query
func (q *Query) And(elem bson.M) *Query {
func (q *Query) And(elem bson.M) (query *Query) {
if q.m == nil {
q.m = bson.M{}
@ -33,57 +33,54 @@ func (q *Query) And(elem bson.M) *Query {
}
// Limiter returns limiter value or nil
func (q *Query) Limiter() *int64 {
func (q *Query) Limiter() (limit *int64) {
if q.limiter == nil {
return nil
return
}
return q.limiter.Limit()
}
// Sorter is a sort rule for a query
func (q *Query) Sorter() interface{} {
func (q *Query) Sorter() (sort interface{}) {
if q.sorter == nil {
return nil
return
}
return q.sorter.Sort()
}
// Skipper is a skipper for a query
func (q *Query) Skipper() *int64 {
func (q *Query) Skipper() (skip *int64) {
if q.skipper == nil {
return nil
return
}
return q.skipper.Skip()
}
// Preloader is a preloader list for a query
func (q *Query) Preloader() (empty bool, preloader []string) {
func (q *Query) Preloader() (ok bool, preloads []string) {
if q.preloader == nil {
return false, nil
}
preloader = q.preloader.Preload()
preloads = q.preloader.Preload()
ok = len(preloads) > 0
if len(preloader) == 0 {
return false, nil
}
return true, preloader
return
}
// Empty checks the query for any content
func (q *Query) Empty() bool {
func (q *Query) Empty() (isEmpty bool) {
return len(q.m) == 0
}
// M returns underlying query map
func (q *Query) M() bson.M {
func (q *Query) M() (m bson.M) {
return q.m
}

@ -2,7 +2,7 @@ package query
// Skipper is a filter to skip the result
type Skipper interface {
Skip() *int64
Skip() (skip *int64)
}
// Skip is a simple implementation of the Skipper filter
@ -11,12 +11,14 @@ type Skip int64
var _ Skipper = Skip(0)
// Skip returns a skip number
func (l Skip) Skip() *int64 {
func (l Skip) Skip() (skip *int64) {
lim := int64(l)
if lim <= 0 {
return nil
if l <= 0 {
return
}
return &lim
skip = new(int64)
*skip = int64(l)
return
}

@ -6,7 +6,7 @@ import (
// Sorter is a filter to sort the data before query
type Sorter interface {
Sort() bson.M
Sort() (sort bson.M)
}
// Sort is a simple implementations of the Sorter filter
@ -15,6 +15,6 @@ type Sort bson.M
var _ Sorter = &Sort{}
// Sort returns a slice of fields which have to be sorted
func (f Sort) Sort() bson.M {
func (f Sort) Sort() (sort bson.M) {
return bson.M(f)
}

@ -5,7 +5,7 @@ import (
)
// IsNil function evaluates the interface value to nil
func IsNil(i interface{}) bool {
func IsNil(i interface{}) (isNil bool) {
type iface struct {
_ unsafe.Pointer
@ -14,8 +14,10 @@ func IsNil(i interface{}) bool {
unpacked := (*iface)(unsafe.Pointer(&i))
if unpacked.ptr == nil {
return true
isNil = true
return
}
return *(*unsafe.Pointer)(unpacked.ptr) == nil
isNil = *(*unsafe.Pointer)(unpacked.ptr) == nil
return
}

Loading…
Cancel
Save