1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-05 04:20:54 +00:00
Beego/orm/orm_object.go

70 lines
1.4 KiB
Go
Raw Normal View History

2013-07-30 12:32:38 +00:00
package orm
import (
"fmt"
"reflect"
)
type insertSet struct {
mi *modelInfo
orm *orm
2013-08-09 05:20:19 +00:00
stmt stmtQuerier
2013-07-30 12:32:38 +00:00
closed bool
}
2013-08-07 11:11:44 +00:00
var _ Inserter = new(insertSet)
func (o *insertSet) Insert(md interface{}) (int64, error) {
2013-07-30 12:32:38 +00:00
if o.closed {
return 0, ErrStmtClosed
}
val := reflect.ValueOf(md)
ind := reflect.Indirect(val)
typ := ind.Type()
name := getFullName(typ)
if val.Kind() != reflect.Ptr {
panic(fmt.Sprintf("<Inserter.Insert> cannot use non-ptr model struct `%s`", name))
}
if name != o.mi.fullName {
panic(fmt.Sprintf("<Inserter.Insert> need model `%s` but found `%s`", o.mi.fullName, name))
2013-07-30 12:32:38 +00:00
}
id, err := o.orm.alias.DbBaser.InsertStmt(o.stmt, o.mi, ind, o.orm.alias.TZ)
2013-07-30 12:32:38 +00:00
if err != nil {
return id, err
}
if id > 0 {
2013-08-07 11:11:44 +00:00
if o.mi.fields.pk.auto {
2013-08-30 04:32:05 +00:00
if o.mi.fields.pk.fieldType&IsPostiveIntegerField > 0 {
ind.Field(o.mi.fields.pk.fieldIndex).SetUint(uint64(id))
} else {
ind.Field(o.mi.fields.pk.fieldIndex).SetInt(id)
}
2013-07-30 12:32:38 +00:00
}
}
return id, nil
}
func (o *insertSet) Close() error {
2013-08-07 11:11:44 +00:00
if o.closed {
return ErrStmtClosed
}
2013-07-30 12:32:38 +00:00
o.closed = true
return o.stmt.Close()
}
func newInsertSet(orm *orm, mi *modelInfo) (Inserter, error) {
bi := new(insertSet)
bi.orm = orm
bi.mi = mi
2013-08-09 05:20:19 +00:00
st, query, err := orm.alias.DbBaser.PrepareInsert(orm.db, mi)
2013-07-30 12:32:38 +00:00
if err != nil {
return nil, err
}
2013-08-09 05:20:19 +00:00
if Debug {
bi.stmt = newStmtQueryLog(orm.alias, st, query)
} else {
bi.stmt = st
}
2013-07-30 12:32:38 +00:00
return bi, nil
}