mdbc/insert.go

104 lines
2.0 KiB
Go
Raw Normal View History

2023-06-22 15:14:51 +00:00
package mdbc
import (
"context"
"gitter.top/common/goref"
"go.mongodb.org/mongo-driver/mongo/options"
)
type insertScope struct {
*scope
*mdbc
ctx context.Context
opts any
docs any
}
type insert interface {
insert(docs any) (*InsertResult, error)
}
type insertOne struct {
*insertScope
}
func (io *insertOne) insert(docs any) (*InsertResult, error) {
result, err := io.database.Collection(io.tableName).InsertOne(io.ctx, docs, io.opts.(*options.InsertOneOptions))
if err != nil {
return nil, err
}
return &InsertResult{id: result.InsertedID}, nil
}
type insertMany struct {
*insertScope
}
func (im *insertMany) insert(docs any) (*InsertResult, error) {
vals, ok := goref.ToInterfaces(docs)
if !ok {
return nil, ErrorNoInsertDocuments
}
result, err := im.database.Collection(im.tableName).InsertMany(im.ctx, vals, im.opts.(*options.InsertManyOptions))
if err != nil {
return nil, err
}
return &InsertResult{id: result.InsertedIDs}, nil
}
type InsertResult struct {
id interface{}
}
func (ir *InsertResult) GetID() string {
val, ok := goref.ToString(ir.id)
if !ok {
}
return val
}
func (ir *InsertResult) GetIDs() []string {
vals, ok := goref.ToStrings(ir.id)
if !ok {
}
return vals
}
func (is *insertScope) SetContext(ctx context.Context) *insertScope {
is.ctx = ctx
return is
}
func (is *insertScope) SetInsertOneOptions(opts options.InsertOneOptions) *insertScope {
2023-06-23 15:09:36 +00:00
is.opts = &opts
2023-06-22 15:14:51 +00:00
return is
}
func (is *insertScope) SetInsertManyOptions(opts options.InsertManyOptions) *insertScope {
2023-06-23 15:09:36 +00:00
is.opts = &opts
2023-06-22 15:14:51 +00:00
return is
}
func (is *insertScope) mergeOptions(isMany bool) *insertScope {
if is.ctx == nil {
is.ctx = context.Background()
}
if is.opts == nil && isMany {
is.opts = &options.InsertManyOptions{}
}
if is.opts == nil && !isMany {
is.opts = &options.InsertOneOptions{}
}
return is
}
func (is *insertScope) Insert(docs any) (*InsertResult, error) {
isMany := goref.IsBaseList(docs)
is.mergeOptions(isMany)
var action insert = &insertOne{is}
if isMany {
action = &insertMany{is}
}
return action.insert(docs)
}