代码拉取完成,页面将自动刷新
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
values []*T
/// 要插入的列
columns []string
/// ON DUPLICATE KEY中使用
onDuplicateKey *OnDuplicateKey
}
func NewInserter[T any](sess session) *Inserter[T] {
return &Inserter[T]{builder: builder{
session: sess,
core: sess.getCore(),
}}
}
func (i *Inserter[T]) Build() (*Query, error) {
//var sb strings.Builder
m, err := i.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.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 {
res := exec(ctx, i.session, i.core, &QueryContext{
Type: Insert,
Builder: i,
})
if res.Result != nil {
return Result{
res: res.Result.(sql.Result),
err: res.Err,
}
}
return Result{
res: nil,
err: res.Err,
}
}
//var _ Handler = (&Inserter[int]{}).execHandler
//func (i *Inserter[T]) execHandler(ctx context.Context, qc *QueryContext) *QueryResult {
// var (
// q *Query
// sqlResult sql.Result
// err error
// )
// q, err = qc.Builder.Build()
// if err != nil {
// return &QueryResult{
// Err: err,
// }
// }
//
// sqlResult, err = i.execContext(ctx, q.SQL, q.Args...)
// if err != nil {
// return &QueryResult{
// Err: err,
// }
// }
//
// return &QueryResult{Result: sqlResult}
//}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。