session_insert.go 15 KB

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