session_insert.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. // Copyright 2016 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. "errors"
  7. "fmt"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "github.com/go-xorm/core"
  12. )
  13. // Insert insert one or more beans
  14. func (session *Session) Insert(beans ...interface{}) (int64, error) {
  15. var affected int64
  16. var err error
  17. if session.IsAutoClose {
  18. defer session.Close()
  19. }
  20. defer session.resetStatement()
  21. for _, bean := range beans {
  22. sliceValue := reflect.Indirect(reflect.ValueOf(bean))
  23. if sliceValue.Kind() == reflect.Slice {
  24. size := sliceValue.Len()
  25. if size > 0 {
  26. if session.Engine.SupportInsertMany() {
  27. cnt, err := session.innerInsertMulti(bean)
  28. if err != nil {
  29. return affected, err
  30. }
  31. affected += cnt
  32. } else {
  33. for i := 0; i < size; i++ {
  34. cnt, err := session.innerInsert(sliceValue.Index(i).Interface())
  35. if err != nil {
  36. return affected, err
  37. }
  38. affected += cnt
  39. }
  40. }
  41. }
  42. } else {
  43. cnt, err := session.innerInsert(bean)
  44. if err != nil {
  45. return affected, err
  46. }
  47. affected += cnt
  48. }
  49. }
  50. return affected, err
  51. }
  52. func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error) {
  53. sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
  54. if sliceValue.Kind() != reflect.Slice {
  55. return 0, errors.New("needs a pointer to a slice")
  56. }
  57. if sliceValue.Len() <= 0 {
  58. return 0, errors.New("could not insert a empty slice")
  59. }
  60. session.Statement.setRefValue(sliceValue.Index(0))
  61. if len(session.Statement.TableName()) <= 0 {
  62. return 0, ErrTableNotFound
  63. }
  64. table := session.Statement.RefTable
  65. size := sliceValue.Len()
  66. var colNames []string
  67. var colMultiPlaces []string
  68. var args []interface{}
  69. var cols []*core.Column
  70. for i := 0; i < size; i++ {
  71. v := sliceValue.Index(i)
  72. vv := reflect.Indirect(v)
  73. elemValue := v.Interface()
  74. var colPlaces []string
  75. // handle BeforeInsertProcessor
  76. // !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi??
  77. for _, closure := range session.beforeClosures {
  78. closure(elemValue)
  79. }
  80. if processor, ok := interface{}(elemValue).(BeforeInsertProcessor); ok {
  81. processor.BeforeInsert()
  82. }
  83. // --
  84. if i == 0 {
  85. for _, col := range table.Columns() {
  86. ptrFieldValue, err := col.ValueOfV(&vv)
  87. if err != nil {
  88. return 0, err
  89. }
  90. fieldValue := *ptrFieldValue
  91. if col.IsAutoIncrement && isZero(fieldValue.Interface()) {
  92. continue
  93. }
  94. if col.MapType == core.ONLYFROMDB {
  95. continue
  96. }
  97. if col.IsDeleted {
  98. continue
  99. }
  100. if session.Statement.ColumnStr != "" {
  101. if _, ok := getFlagForColumn(session.Statement.columnMap, col); !ok {
  102. continue
  103. }
  104. }
  105. if session.Statement.OmitStr != "" {
  106. if _, ok := getFlagForColumn(session.Statement.columnMap, col); ok {
  107. continue
  108. }
  109. }
  110. if (col.IsCreated || col.IsUpdated) && session.Statement.UseAutoTime {
  111. val, t := session.Engine.NowTime2(col.SQLType.Name)
  112. args = append(args, val)
  113. var colName = col.Name
  114. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  115. col := table.GetColumn(colName)
  116. setColumnTime(bean, col, t)
  117. })
  118. } else if col.IsVersion && session.Statement.checkVersion {
  119. args = append(args, 1)
  120. var colName = col.Name
  121. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  122. col := table.GetColumn(colName)
  123. setColumnInt(bean, col, 1)
  124. })
  125. } else {
  126. arg, err := session.value2Interface(col, fieldValue)
  127. if err != nil {
  128. return 0, err
  129. }
  130. args = append(args, arg)
  131. }
  132. colNames = append(colNames, col.Name)
  133. cols = append(cols, col)
  134. colPlaces = append(colPlaces, "?")
  135. }
  136. } else {
  137. for _, col := range cols {
  138. ptrFieldValue, err := col.ValueOfV(&vv)
  139. if err != nil {
  140. return 0, err
  141. }
  142. fieldValue := *ptrFieldValue
  143. if col.IsAutoIncrement && isZero(fieldValue.Interface()) {
  144. continue
  145. }
  146. if col.MapType == core.ONLYFROMDB {
  147. continue
  148. }
  149. if col.IsDeleted {
  150. continue
  151. }
  152. if session.Statement.ColumnStr != "" {
  153. if _, ok := getFlagForColumn(session.Statement.columnMap, col); !ok {
  154. continue
  155. }
  156. }
  157. if session.Statement.OmitStr != "" {
  158. if _, ok := getFlagForColumn(session.Statement.columnMap, col); ok {
  159. continue
  160. }
  161. }
  162. if (col.IsCreated || col.IsUpdated) && session.Statement.UseAutoTime {
  163. val, t := session.Engine.NowTime2(col.SQLType.Name)
  164. args = append(args, val)
  165. var colName = col.Name
  166. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  167. col := table.GetColumn(colName)
  168. setColumnTime(bean, col, t)
  169. })
  170. } else if col.IsVersion && session.Statement.checkVersion {
  171. args = append(args, 1)
  172. var colName = col.Name
  173. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  174. col := table.GetColumn(colName)
  175. setColumnInt(bean, col, 1)
  176. })
  177. } else {
  178. arg, err := session.value2Interface(col, fieldValue)
  179. if err != nil {
  180. return 0, err
  181. }
  182. args = append(args, arg)
  183. }
  184. colPlaces = append(colPlaces, "?")
  185. }
  186. }
  187. colMultiPlaces = append(colMultiPlaces, strings.Join(colPlaces, ", "))
  188. }
  189. cleanupProcessorsClosures(&session.beforeClosures)
  190. statement := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)",
  191. session.Engine.Quote(session.Statement.TableName()),
  192. session.Engine.QuoteStr(),
  193. strings.Join(colNames, session.Engine.QuoteStr()+", "+session.Engine.QuoteStr()),
  194. session.Engine.QuoteStr(),
  195. strings.Join(colMultiPlaces, "),("))
  196. res, err := session.exec(statement, args...)
  197. if err != nil {
  198. return 0, err
  199. }
  200. if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache {
  201. session.cacheInsert(session.Statement.TableName())
  202. }
  203. lenAfterClosures := len(session.afterClosures)
  204. for i := 0; i < size; i++ {
  205. elemValue := reflect.Indirect(sliceValue.Index(i)).Addr().Interface()
  206. // handle AfterInsertProcessor
  207. if session.IsAutoCommit {
  208. // !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi??
  209. for _, closure := range session.afterClosures {
  210. closure(elemValue)
  211. }
  212. if processor, ok := interface{}(elemValue).(AfterInsertProcessor); ok {
  213. processor.AfterInsert()
  214. }
  215. } else {
  216. if lenAfterClosures > 0 {
  217. if value, has := session.afterInsertBeans[elemValue]; has && value != nil {
  218. *value = append(*value, session.afterClosures...)
  219. } else {
  220. afterClosures := make([]func(interface{}), lenAfterClosures)
  221. copy(afterClosures, session.afterClosures)
  222. session.afterInsertBeans[elemValue] = &afterClosures
  223. }
  224. } else {
  225. if _, ok := interface{}(elemValue).(AfterInsertProcessor); ok {
  226. session.afterInsertBeans[elemValue] = nil
  227. }
  228. }
  229. }
  230. }
  231. cleanupProcessorsClosures(&session.afterClosures)
  232. return res.RowsAffected()
  233. }
  234. // InsertMulti insert multiple records
  235. func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error) {
  236. defer session.resetStatement()
  237. if session.IsAutoClose {
  238. defer session.Close()
  239. }
  240. sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
  241. if sliceValue.Kind() != reflect.Slice {
  242. return 0, ErrParamsType
  243. }
  244. if sliceValue.Len() <= 0 {
  245. return 0, nil
  246. }
  247. return session.innerInsertMulti(rowsSlicePtr)
  248. }
  249. func (session *Session) innerInsert(bean interface{}) (int64, error) {
  250. session.Statement.setRefValue(rValue(bean))
  251. if len(session.Statement.TableName()) <= 0 {
  252. return 0, ErrTableNotFound
  253. }
  254. table := session.Statement.RefTable
  255. // handle BeforeInsertProcessor
  256. for _, closure := range session.beforeClosures {
  257. closure(bean)
  258. }
  259. cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used
  260. if processor, ok := interface{}(bean).(BeforeInsertProcessor); ok {
  261. processor.BeforeInsert()
  262. }
  263. // --
  264. colNames, args, err := genCols(session.Statement.RefTable, session, bean, false, false)
  265. if err != nil {
  266. return 0, err
  267. }
  268. // insert expr columns, override if exists
  269. exprColumns := session.Statement.getExpr()
  270. exprColVals := make([]string, 0, len(exprColumns))
  271. for _, v := range exprColumns {
  272. // remove the expr columns
  273. for i, colName := range colNames {
  274. if colName == v.colName {
  275. colNames = append(colNames[:i], colNames[i+1:]...)
  276. args = append(args[:i], args[i+1:]...)
  277. }
  278. }
  279. // append expr column to the end
  280. colNames = append(colNames, v.colName)
  281. exprColVals = append(exprColVals, v.expr)
  282. }
  283. colPlaces := strings.Repeat("?, ", len(colNames)-len(exprColumns))
  284. if len(exprColVals) > 0 {
  285. colPlaces = colPlaces + strings.Join(exprColVals, ", ")
  286. } else {
  287. colPlaces = colPlaces[0 : len(colPlaces)-2]
  288. }
  289. sqlStr := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)",
  290. session.Engine.Quote(session.Statement.TableName()),
  291. session.Engine.QuoteStr(),
  292. strings.Join(colNames, session.Engine.Quote(", ")),
  293. session.Engine.QuoteStr(),
  294. colPlaces)
  295. handleAfterInsertProcessorFunc := func(bean interface{}) {
  296. if session.IsAutoCommit {
  297. for _, closure := range session.afterClosures {
  298. closure(bean)
  299. }
  300. if processor, ok := interface{}(bean).(AfterInsertProcessor); ok {
  301. processor.AfterInsert()
  302. }
  303. } else {
  304. lenAfterClosures := len(session.afterClosures)
  305. if lenAfterClosures > 0 {
  306. if value, has := session.afterInsertBeans[bean]; has && value != nil {
  307. *value = append(*value, session.afterClosures...)
  308. } else {
  309. afterClosures := make([]func(interface{}), lenAfterClosures)
  310. copy(afterClosures, session.afterClosures)
  311. session.afterInsertBeans[bean] = &afterClosures
  312. }
  313. } else {
  314. if _, ok := interface{}(bean).(AfterInsertProcessor); ok {
  315. session.afterInsertBeans[bean] = nil
  316. }
  317. }
  318. }
  319. cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
  320. }
  321. // for postgres, many of them didn't implement lastInsertId, so we should
  322. // implemented it ourself.
  323. if session.Engine.dialect.DBType() == core.ORACLE && len(table.AutoIncrement) > 0 {
  324. //assert table.AutoIncrement != ""
  325. res, err := session.query("select seq_atable.currval from dual", args...)
  326. if err != nil {
  327. return 0, err
  328. }
  329. handleAfterInsertProcessorFunc(bean)
  330. if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache {
  331. session.cacheInsert(session.Statement.TableName())
  332. }
  333. if table.Version != "" && session.Statement.checkVersion {
  334. verValue, err := table.VersionColumn().ValueOf(bean)
  335. if err != nil {
  336. session.Engine.logger.Error(err)
  337. } else if verValue.IsValid() && verValue.CanSet() {
  338. verValue.SetInt(1)
  339. }
  340. }
  341. if len(res) < 1 {
  342. return 0, errors.New("insert no error but not returned id")
  343. }
  344. idByte := res[0][table.AutoIncrement]
  345. id, err := strconv.ParseInt(string(idByte), 10, 64)
  346. if err != nil || id <= 0 {
  347. return 1, err
  348. }
  349. aiValue, err := table.AutoIncrColumn().ValueOf(bean)
  350. if err != nil {
  351. session.Engine.logger.Error(err)
  352. }
  353. if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
  354. return 1, nil
  355. }
  356. aiValue.Set(int64ToIntValue(id, aiValue.Type()))
  357. return 1, nil
  358. } else if session.Engine.dialect.DBType() == core.POSTGRES && len(table.AutoIncrement) > 0 {
  359. //assert table.AutoIncrement != ""
  360. sqlStr = sqlStr + " RETURNING " + session.Engine.Quote(table.AutoIncrement)
  361. res, err := session.query(sqlStr, args...)
  362. if err != nil {
  363. return 0, err
  364. }
  365. handleAfterInsertProcessorFunc(bean)
  366. if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache {
  367. session.cacheInsert(session.Statement.TableName())
  368. }
  369. if table.Version != "" && session.Statement.checkVersion {
  370. verValue, err := table.VersionColumn().ValueOf(bean)
  371. if err != nil {
  372. session.Engine.logger.Error(err)
  373. } else if verValue.IsValid() && verValue.CanSet() {
  374. verValue.SetInt(1)
  375. }
  376. }
  377. if len(res) < 1 {
  378. return 0, errors.New("insert no error but not returned id")
  379. }
  380. idByte := res[0][table.AutoIncrement]
  381. id, err := strconv.ParseInt(string(idByte), 10, 64)
  382. if err != nil || id <= 0 {
  383. return 1, err
  384. }
  385. aiValue, err := table.AutoIncrColumn().ValueOf(bean)
  386. if err != nil {
  387. session.Engine.logger.Error(err)
  388. }
  389. if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
  390. return 1, nil
  391. }
  392. aiValue.Set(int64ToIntValue(id, aiValue.Type()))
  393. return 1, nil
  394. } else {
  395. res, err := session.exec(sqlStr, args...)
  396. if err != nil {
  397. return 0, err
  398. }
  399. defer handleAfterInsertProcessorFunc(bean)
  400. if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache {
  401. session.cacheInsert(session.Statement.TableName())
  402. }
  403. if table.Version != "" && session.Statement.checkVersion {
  404. verValue, err := table.VersionColumn().ValueOf(bean)
  405. if err != nil {
  406. session.Engine.logger.Error(err)
  407. } else if verValue.IsValid() && verValue.CanSet() {
  408. verValue.SetInt(1)
  409. }
  410. }
  411. if table.AutoIncrement == "" {
  412. return res.RowsAffected()
  413. }
  414. var id int64
  415. id, err = res.LastInsertId()
  416. if err != nil || id <= 0 {
  417. return res.RowsAffected()
  418. }
  419. aiValue, err := table.AutoIncrColumn().ValueOf(bean)
  420. if err != nil {
  421. session.Engine.logger.Error(err)
  422. }
  423. if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
  424. return res.RowsAffected()
  425. }
  426. aiValue.Set(int64ToIntValue(id, aiValue.Type()))
  427. return res.RowsAffected()
  428. }
  429. }
  430. // InsertOne insert only one struct into database as a record.
  431. // The in parameter bean must a struct or a point to struct. The return
  432. // parameter is inserted and error
  433. func (session *Session) InsertOne(bean interface{}) (int64, error) {
  434. defer session.resetStatement()
  435. if session.IsAutoClose {
  436. defer session.Close()
  437. }
  438. return session.innerInsert(bean)
  439. }
  440. func (session *Session) cacheInsert(tables ...string) error {
  441. if session.Statement.RefTable == nil {
  442. return ErrCacheFailed
  443. }
  444. table := session.Statement.RefTable
  445. cacher := session.Engine.getCacher2(table)
  446. for _, t := range tables {
  447. session.Engine.logger.Debug("[cache] clear sql:", t)
  448. cacher.ClearIds(t)
  449. }
  450. return nil
  451. }