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

80 lines
1.8 KiB
Go
Raw Normal View History

2014-04-12 05:18:18 +00:00
// Beego (http://beego.me/)
// @description beego is an open-source, high-performance web framework for the Go programming language.
// @link http://github.com/astaxie/beego for the canonical source repository
// @license http://github.com/astaxie/beego/blob/master/LICENSE
// @authors slene
2013-07-30 12:32:38 +00:00
package orm
import (
"fmt"
"reflect"
)
2014-01-17 15:28:54 +00:00
// an insert queryer struct
2013-07-30 12:32:38 +00:00
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)
2014-01-17 15:28:54 +00:00
// insert model ignore it's registered or not.
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 {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("<Inserter.Insert> cannot use non-ptr model struct `%s`", name))
}
if name != o.mi.fullName {
2013-10-09 03:37:16 +00:00
panic(fmt.Errorf("<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
}
2014-01-17 15:28:54 +00:00
// close insert queryer statement
2013-07-30 12:32:38 +00:00
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()
}
2014-01-17 15:28:54 +00:00
// create new insert queryer.
2013-07-30 12:32:38 +00:00
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
}