1
0

orm_object.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. package orm
  15. import (
  16. "fmt"
  17. "reflect"
  18. )
  19. // an insert queryer struct
  20. type insertSet struct {
  21. mi *modelInfo
  22. orm *orm
  23. stmt stmtQuerier
  24. closed bool
  25. }
  26. var _ Inserter = new(insertSet)
  27. // insert model ignore it's registered or not.
  28. func (o *insertSet) Insert(md interface{}) (int64, error) {
  29. if o.closed {
  30. return 0, ErrStmtClosed
  31. }
  32. val := reflect.ValueOf(md)
  33. ind := reflect.Indirect(val)
  34. typ := ind.Type()
  35. name := getFullName(typ)
  36. if val.Kind() != reflect.Ptr {
  37. panic(fmt.Errorf("<Inserter.Insert> cannot use non-ptr model struct `%s`", name))
  38. }
  39. if name != o.mi.fullName {
  40. panic(fmt.Errorf("<Inserter.Insert> need model `%s` but found `%s`", o.mi.fullName, name))
  41. }
  42. id, err := o.orm.alias.DbBaser.InsertStmt(o.stmt, o.mi, ind, o.orm.alias.TZ)
  43. if err != nil {
  44. return id, err
  45. }
  46. if id > 0 {
  47. if o.mi.fields.pk.auto {
  48. if o.mi.fields.pk.fieldType&IsPositiveIntegerField > 0 {
  49. ind.FieldByIndex(o.mi.fields.pk.fieldIndex).SetUint(uint64(id))
  50. } else {
  51. ind.FieldByIndex(o.mi.fields.pk.fieldIndex).SetInt(id)
  52. }
  53. }
  54. }
  55. return id, nil
  56. }
  57. // close insert queryer statement
  58. func (o *insertSet) Close() error {
  59. if o.closed {
  60. return ErrStmtClosed
  61. }
  62. o.closed = true
  63. return o.stmt.Close()
  64. }
  65. // create new insert queryer.
  66. func newInsertSet(orm *orm, mi *modelInfo) (Inserter, error) {
  67. bi := new(insertSet)
  68. bi.orm = orm
  69. bi.mi = mi
  70. st, query, err := orm.alias.DbBaser.PrepareInsert(orm.db, mi)
  71. if err != nil {
  72. return nil, err
  73. }
  74. if Debug {
  75. bi.stmt = newStmtQueryLog(orm.alias, st, query)
  76. } else {
  77. bi.stmt = st
  78. }
  79. return bi, nil
  80. }