代码拉取完成,页面将自动刷新
package orm
import (
"context"
"database/sql"
"gitee.com/mosache/YFrame/orm/internal/errs"
model "gitee.com/mosache/YFrame/orm/schema"
)
type Inserter[T any] struct {
builder
db *DB
values []*T
/// 要插入的列
columns []string
/// ON DUPLICATE KEY中使用
onDuplicateKey *OnDuplicateKey
}
func NewInserter[T any](db *DB) *Inserter[T] {
return &Inserter[T]{db: db, builder: builder{
dialect: db.dialect,
quoter: db.quoter,
}}
}
func (i *Inserter[T]) Build() (*Query, error) {
//var sb strings.Builder
m, err := i.db.r.Get(new(T))
if err != nil {
return nil, err
}
i.m = m
i.sb.WriteString("INSERT INTO")
i.sb.WriteString(" ")
i.Quoter(i.m.TableName)
fields := i.m.Fields
if len(i.columns) > 0 {
fields = make([]*model.Field, 0, len(i.columns))
for _, e := range i.columns {
field, ok := i.m.FieldMap[e]
if !ok {
return nil, errs.NewErrUnknownField(e)
}
fields = append(fields, field)
}
}
i.sb.WriteString("(")
for idx, e := range fields {
if idx != 0 {
i.sb.WriteString(",")
}
i.sb.WriteString("`")
i.sb.WriteString(e.ColumnName)
i.sb.WriteString("`")
}
i.sb.WriteString(") ")
i.sb.WriteString("VALUES ")
//args := make([]any, 0, len(i.values)*len(i.m.Fields))
for idx, val := range i.values {
if idx != 0 {
i.sb.WriteString(",")
}
i.sb.WriteString("(")
for fIdx, e := range fields {
if fIdx != 0 {
i.sb.WriteString(",")
}
i.sb.WriteString("?")
valuer := i.db.creator(i.m, val)
var arg any
if arg, err = valuer.Field(e.GoName); err != nil {
return nil, err
}
i.args = append(i.args, arg)
}
i.sb.WriteString(")")
}
// assigns
if i.onDuplicateKey != nil {
if err = i.dialect.BuildOnDuplicateKey(&i.builder, i.onDuplicateKey); err != nil {
return nil, err
}
}
i.sb.WriteString(";")
return &Query{
SQL: i.sb.String(),
Args: i.args,
}, nil
}
func (i *Inserter[T]) Exec(ctx context.Context) Result {
var (
r Result
q *Query
sqlResult sql.Result
err error
)
q, err = i.Build()
if err != nil {
r.Err = err
return r
}
sqlResult, err = i.db.db.ExecContext(ctx, q.SQL, q.Args...)
if err != nil {
r.Err = err
return r
}
r.Res = sqlResult
return r
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。