2023-09-10 16:07:03 +00:00
|
|
|
package sdbc
|
|
|
|
|
|
|
|
import "context"
|
|
|
|
|
2023-09-16 10:09:34 +00:00
|
|
|
type _insert struct {
|
2023-09-10 16:07:03 +00:00
|
|
|
scope *scope
|
|
|
|
sdbc *sdbc
|
|
|
|
ctx context.Context
|
|
|
|
selectOpts []interface{}
|
|
|
|
omitOpts []string
|
|
|
|
}
|
|
|
|
|
2023-09-16 10:09:34 +00:00
|
|
|
func (i *_insert) SetContext(ctx context.Context) *_insert {
|
2023-09-10 16:07:03 +00:00
|
|
|
i.ctx = ctx
|
2023-09-16 10:09:34 +00:00
|
|
|
return i
|
2023-09-10 16:07:03 +00:00
|
|
|
}
|
|
|
|
|
2023-09-16 10:09:34 +00:00
|
|
|
// SetSelect 只插入字段
|
|
|
|
func (i *_insert) SetSelect(selects ...any) *_insert {
|
2023-09-10 16:07:03 +00:00
|
|
|
i.selectOpts = selects
|
2023-09-16 10:09:34 +00:00
|
|
|
return i
|
2023-09-10 16:07:03 +00:00
|
|
|
}
|
|
|
|
|
2023-09-16 10:09:34 +00:00
|
|
|
// SetOmit 忽略字段
|
|
|
|
func (i *_insert) SetOmit(omits ...string) *_insert {
|
2023-09-10 16:07:03 +00:00
|
|
|
i.omitOpts = omits
|
2023-09-16 10:09:34 +00:00
|
|
|
return i
|
2023-09-10 16:07:03 +00:00
|
|
|
}
|
|
|
|
|
2023-09-16 10:09:34 +00:00
|
|
|
// Insert 插入数据
|
|
|
|
func (i *_insert) Insert(docs any) error {
|
2023-09-10 16:07:03 +00:00
|
|
|
db := i.sdbc.client
|
|
|
|
if len(i.selectOpts) != 0 {
|
2023-09-16 10:09:34 +00:00
|
|
|
db = db.Select(i.selectOpts[0], i.selectOpts[1:]...)
|
2023-09-10 16:07:03 +00:00
|
|
|
}
|
|
|
|
if len(i.omitOpts) != 0 {
|
2023-09-16 10:09:34 +00:00
|
|
|
db = db.Omit(i.omitOpts...)
|
2023-09-10 16:07:03 +00:00
|
|
|
}
|
2023-09-16 10:09:34 +00:00
|
|
|
return db.Model(i.scope.model.ptr()).Create(docs).Error
|
2023-09-10 16:07:03 +00:00
|
|
|
}
|
|
|
|
|
2023-09-16 10:09:34 +00:00
|
|
|
// InsertBatch 按批插入数据
|
|
|
|
func (i *_insert) InsertBatch(docs any) error {
|
|
|
|
db := i.sdbc.client
|
|
|
|
if len(i.selectOpts) != 0 {
|
|
|
|
db = db.Select(i.selectOpts[0], i.selectOpts[1:]...)
|
|
|
|
}
|
|
|
|
if len(i.omitOpts) != 0 {
|
|
|
|
db = db.Omit(i.omitOpts...)
|
|
|
|
}
|
|
|
|
return db.Model(i.scope.model.ptr()).CreateInBatches(docs, 1000).Error
|
2023-09-10 16:07:03 +00:00
|
|
|
}
|