2 Star 1 Fork 1

mosache/YFrame

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

搜索帮助