2 Star 1 Fork 1

mosache/YFrame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
inserter.go 2.62 KB
一键复制 编辑 原始数据 按行查看 历史
ヤ沒脩袮兲︶ 提交于 2023-07-07 18:26 . temp
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}
//}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/mosache/YFrame.git
git@gitee.com:mosache/YFrame.git
mosache
YFrame
YFrame
v0.1.48

搜索帮助

0d507c66 1850385 C8b1a773 1850385