github.com/astaxie/beego@v1.12.3/orm/orm_object.go (about)

     1  // Copyright 2014 beego Author. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package orm
    16  
    17  import (
    18  	"fmt"
    19  	"reflect"
    20  )
    21  
    22  // an insert queryer struct
    23  type insertSet struct {
    24  	mi     *modelInfo
    25  	orm    *orm
    26  	stmt   stmtQuerier
    27  	closed bool
    28  }
    29  
    30  var _ Inserter = new(insertSet)
    31  
    32  // insert model ignore it's registered or not.
    33  func (o *insertSet) Insert(md interface{}) (int64, error) {
    34  	if o.closed {
    35  		return 0, ErrStmtClosed
    36  	}
    37  	val := reflect.ValueOf(md)
    38  	ind := reflect.Indirect(val)
    39  	typ := ind.Type()
    40  	name := getFullName(typ)
    41  	if val.Kind() != reflect.Ptr {
    42  		panic(fmt.Errorf("<Inserter.Insert> cannot use non-ptr model struct `%s`", name))
    43  	}
    44  	if name != o.mi.fullName {
    45  		panic(fmt.Errorf("<Inserter.Insert> need model `%s` but found `%s`", o.mi.fullName, name))
    46  	}
    47  	id, err := o.orm.alias.DbBaser.InsertStmt(o.stmt, o.mi, ind, o.orm.alias.TZ)
    48  	if err != nil {
    49  		return id, err
    50  	}
    51  	if id > 0 {
    52  		if o.mi.fields.pk.auto {
    53  			if o.mi.fields.pk.fieldType&IsPositiveIntegerField > 0 {
    54  				ind.FieldByIndex(o.mi.fields.pk.fieldIndex).SetUint(uint64(id))
    55  			} else {
    56  				ind.FieldByIndex(o.mi.fields.pk.fieldIndex).SetInt(id)
    57  			}
    58  		}
    59  	}
    60  	return id, nil
    61  }
    62  
    63  // close insert queryer statement
    64  func (o *insertSet) Close() error {
    65  	if o.closed {
    66  		return ErrStmtClosed
    67  	}
    68  	o.closed = true
    69  	return o.stmt.Close()
    70  }
    71  
    72  // create new insert queryer.
    73  func newInsertSet(orm *orm, mi *modelInfo) (Inserter, error) {
    74  	bi := new(insertSet)
    75  	bi.orm = orm
    76  	bi.mi = mi
    77  	st, query, err := orm.alias.DbBaser.PrepareInsert(orm.db, mi)
    78  	if err != nil {
    79  		return nil, err
    80  	}
    81  	if Debug {
    82  		bi.stmt = newStmtQueryLog(orm.alias, st, query)
    83  	} else {
    84  		bi.stmt = st
    85  	}
    86  	return bi, nil
    87  }