Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle https://xorm.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1362 lines
29KB

  1. // Copyright 2017 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. "sync"
  9. "testing"
  10. "time"
  11. "github.com/stretchr/testify/assert"
  12. "xorm.io/core"
  13. )
  14. func TestUpdateMap(t *testing.T) {
  15. assert.NoError(t, prepareEngine())
  16. type UpdateTable struct {
  17. Id int64
  18. Name string
  19. Age int
  20. }
  21. assert.NoError(t, testEngine.Sync2(new(UpdateTable)))
  22. var tb = UpdateTable{
  23. Name: "test",
  24. Age: 35,
  25. }
  26. _, err := testEngine.Insert(&tb)
  27. assert.NoError(t, err)
  28. cnt, err := testEngine.Table("update_table").Where("id = ?", tb.Id).Update(map[string]interface{}{
  29. "name": "test2",
  30. "age": 36,
  31. })
  32. assert.NoError(t, err)
  33. assert.EqualValues(t, 1, cnt)
  34. }
  35. func TestUpdateLimit(t *testing.T) {
  36. assert.NoError(t, prepareEngine())
  37. type UpdateTable2 struct {
  38. Id int64
  39. Name string
  40. Age int
  41. }
  42. assert.NoError(t, testEngine.Sync2(new(UpdateTable2)))
  43. var tb = UpdateTable2{
  44. Name: "test1",
  45. Age: 35,
  46. }
  47. cnt, err := testEngine.Insert(&tb)
  48. assert.NoError(t, err)
  49. assert.EqualValues(t, 1, cnt)
  50. tb.Name = "test2"
  51. tb.Id = 0
  52. cnt, err = testEngine.Insert(&tb)
  53. assert.NoError(t, err)
  54. assert.EqualValues(t, 1, cnt)
  55. cnt, err = testEngine.OrderBy("name desc").Limit(1).Update(&UpdateTable2{
  56. Age: 30,
  57. })
  58. assert.NoError(t, err)
  59. assert.EqualValues(t, 1, cnt)
  60. var uts []UpdateTable2
  61. err = testEngine.Find(&uts)
  62. assert.NoError(t, err)
  63. assert.EqualValues(t, 2, len(uts))
  64. assert.EqualValues(t, 35, uts[0].Age)
  65. assert.EqualValues(t, 30, uts[1].Age)
  66. }
  67. type ForUpdate struct {
  68. Id int64 `xorm:"pk"`
  69. Name string
  70. }
  71. func setupForUpdate(engine EngineInterface) error {
  72. v := new(ForUpdate)
  73. err := testEngine.DropTables(v)
  74. if err != nil {
  75. return err
  76. }
  77. err = testEngine.CreateTables(v)
  78. if err != nil {
  79. return err
  80. }
  81. list := []ForUpdate{
  82. {1, "data1"},
  83. {2, "data2"},
  84. {3, "data3"},
  85. }
  86. for _, f := range list {
  87. _, err = testEngine.Insert(f)
  88. if err != nil {
  89. return err
  90. }
  91. }
  92. return nil
  93. }
  94. func TestForUpdate(t *testing.T) {
  95. if *ignoreSelectUpdate {
  96. return
  97. }
  98. err := setupForUpdate(testEngine)
  99. if err != nil {
  100. t.Error(err)
  101. return
  102. }
  103. session1 := testEngine.NewSession()
  104. session2 := testEngine.NewSession()
  105. session3 := testEngine.NewSession()
  106. defer session1.Close()
  107. defer session2.Close()
  108. defer session3.Close()
  109. // start transaction
  110. err = session1.Begin()
  111. if err != nil {
  112. t.Error(err)
  113. return
  114. }
  115. // use lock
  116. fList := make([]ForUpdate, 0)
  117. session1.ForUpdate()
  118. session1.Where("(id) = ?", 1)
  119. err = session1.Find(&fList)
  120. switch {
  121. case err != nil:
  122. t.Error(err)
  123. return
  124. case len(fList) != 1:
  125. t.Errorf("find not returned single row")
  126. return
  127. case fList[0].Name != "data1":
  128. t.Errorf("for_update.name must be `data1`")
  129. return
  130. }
  131. // wait for lock
  132. wg := &sync.WaitGroup{}
  133. // lock is used
  134. wg.Add(1)
  135. go func() {
  136. f2 := new(ForUpdate)
  137. session2.Where("(id) = ?", 1).ForUpdate()
  138. has, err := session2.Get(f2) // wait release lock
  139. switch {
  140. case err != nil:
  141. t.Error(err)
  142. case !has:
  143. t.Errorf("cannot find target row. for_update.id = 1")
  144. case f2.Name != "updated by session1":
  145. t.Errorf("read lock failed")
  146. }
  147. wg.Done()
  148. }()
  149. // lock is NOT used
  150. wg.Add(1)
  151. go func() {
  152. f3 := new(ForUpdate)
  153. session3.Where("(id) = ?", 1)
  154. has, err := session3.Get(f3) // wait release lock
  155. switch {
  156. case err != nil:
  157. t.Error(err)
  158. case !has:
  159. t.Errorf("cannot find target row. for_update.id = 1")
  160. case f3.Name != "data1":
  161. t.Errorf("read lock failed")
  162. }
  163. wg.Done()
  164. }()
  165. // wait for go rountines
  166. time.Sleep(50 * time.Millisecond)
  167. f := new(ForUpdate)
  168. f.Name = "updated by session1"
  169. session1.Where("(id) = ?", 1)
  170. session1.Update(f)
  171. // release lock
  172. err = session1.Commit()
  173. if err != nil {
  174. t.Error(err)
  175. return
  176. }
  177. wg.Wait()
  178. }
  179. func TestWithIn(t *testing.T) {
  180. type temp3 struct {
  181. Id int64 `xorm:"Id pk autoincr"`
  182. Name string `xorm:"Name"`
  183. Test bool `xorm:"Test"`
  184. }
  185. assert.NoError(t, prepareEngine())
  186. assert.NoError(t, testEngine.Sync(new(temp3)))
  187. testEngine.Insert(&[]temp3{
  188. {
  189. Name: "user1",
  190. },
  191. {
  192. Name: "user1",
  193. },
  194. {
  195. Name: "user1",
  196. },
  197. })
  198. cnt, err := testEngine.In("Id", 1, 2, 3, 4).Update(&temp3{Name: "aa"}, &temp3{Name: "user1"})
  199. assert.NoError(t, err)
  200. assert.EqualValues(t, 3, cnt)
  201. }
  202. type Condi map[string]interface{}
  203. type UpdateAllCols struct {
  204. Id int64
  205. Bool bool
  206. String string
  207. Ptr *string
  208. }
  209. type UpdateMustCols struct {
  210. Id int64
  211. Bool bool
  212. String string
  213. }
  214. type UpdateIncr struct {
  215. Id int64
  216. Cnt int
  217. Name string
  218. }
  219. type Article struct {
  220. Id int32 `xorm:"pk INT autoincr"`
  221. Name string `xorm:"VARCHAR(45)"`
  222. Img string `xorm:"VARCHAR(100)"`
  223. Aside string `xorm:"VARCHAR(200)"`
  224. Desc string `xorm:"VARCHAR(200)"`
  225. Content string `xorm:"TEXT"`
  226. Status int8 `xorm:"TINYINT(4)"`
  227. }
  228. func TestUpdateMap2(t *testing.T) {
  229. assert.NoError(t, prepareEngine())
  230. assertSync(t, new(UpdateMustCols))
  231. _, err := testEngine.Table("update_must_cols").Where("id =?", 1).Update(map[string]interface{}{
  232. "bool": true,
  233. })
  234. if err != nil {
  235. t.Error(err)
  236. panic(err)
  237. }
  238. }
  239. func TestUpdate1(t *testing.T) {
  240. assert.NoError(t, prepareEngine())
  241. assertSync(t, new(Userinfo))
  242. _, err := testEngine.Insert(&Userinfo{
  243. Username: "user1",
  244. })
  245. var ori Userinfo
  246. has, err := testEngine.Get(&ori)
  247. if err != nil {
  248. t.Error(err)
  249. panic(err)
  250. }
  251. if !has {
  252. t.Error(errors.New("not exist"))
  253. panic(errors.New("not exist"))
  254. }
  255. // update by id
  256. user := Userinfo{Username: "xxx", Height: 1.2}
  257. cnt, err := testEngine.ID(ori.Uid).Update(&user)
  258. assert.NoError(t, err)
  259. assert.EqualValues(t, 1, cnt)
  260. condi := Condi{"username": "zzz", "departname": ""}
  261. cnt, err = testEngine.Table(&user).ID(ori.Uid).Update(&condi)
  262. assert.NoError(t, err)
  263. assert.EqualValues(t, 1, cnt)
  264. cnt, err = testEngine.Update(&Userinfo{Username: "yyy"}, &user)
  265. assert.NoError(t, err)
  266. total, err := testEngine.Count(&user)
  267. assert.NoError(t, err)
  268. assert.EqualValues(t, cnt, total)
  269. // nullable update
  270. {
  271. user := &Userinfo{Username: "not null data", Height: 180.5}
  272. _, err := testEngine.Insert(user)
  273. if err != nil {
  274. t.Error(err)
  275. panic(err)
  276. }
  277. userID := user.Uid
  278. has, err := testEngine.ID(userID).
  279. And("username = ?", user.Username).
  280. And("height = ?", user.Height).
  281. And("departname = ?", "").
  282. And("detail_id = ?", 0).
  283. And("is_man = ?", 0).
  284. Get(&Userinfo{})
  285. if err != nil {
  286. t.Error(err)
  287. panic(err)
  288. }
  289. if !has {
  290. err = errors.New("cannot insert properly")
  291. t.Error(err)
  292. panic(err)
  293. }
  294. updatedUser := &Userinfo{Username: "null data"}
  295. cnt, err = testEngine.ID(userID).
  296. Nullable("height", "departname", "is_man", "created").
  297. Update(updatedUser)
  298. if err != nil {
  299. t.Error(err)
  300. panic(err)
  301. }
  302. if cnt != 1 {
  303. err = errors.New("update not returned 1")
  304. t.Error(err)
  305. panic(err)
  306. }
  307. has, err = testEngine.ID(userID).
  308. And("username = ?", updatedUser.Username).
  309. And("height IS NULL").
  310. And("departname IS NULL").
  311. And("is_man IS NULL").
  312. And("created IS NULL").
  313. And("detail_id = ?", 0).
  314. Get(&Userinfo{})
  315. if err != nil {
  316. t.Error(err)
  317. panic(err)
  318. }
  319. if !has {
  320. err = errors.New("cannot update with null properly")
  321. t.Error(err)
  322. panic(err)
  323. }
  324. cnt, err = testEngine.ID(userID).Delete(&Userinfo{})
  325. if err != nil {
  326. t.Error(err)
  327. panic(err)
  328. }
  329. if cnt != 1 {
  330. err = errors.New("delete not returned 1")
  331. t.Error(err)
  332. panic(err)
  333. }
  334. }
  335. err = testEngine.StoreEngine("Innodb").Sync2(&Article{})
  336. if err != nil {
  337. t.Error(err)
  338. panic(err)
  339. }
  340. defer func() {
  341. err = testEngine.DropTables(&Article{})
  342. if err != nil {
  343. t.Error(err)
  344. panic(err)
  345. }
  346. }()
  347. a := &Article{0, "1", "2", "3", "4", "5", 2}
  348. cnt, err = testEngine.Insert(a)
  349. if err != nil {
  350. t.Error(err)
  351. panic(err)
  352. }
  353. if cnt != 1 {
  354. err = errors.New(fmt.Sprintf("insert not returned 1 but %d", cnt))
  355. t.Error(err)
  356. panic(err)
  357. }
  358. if a.Id == 0 {
  359. err = errors.New("insert returned id is 0")
  360. t.Error(err)
  361. panic(err)
  362. }
  363. cnt, err = testEngine.ID(a.Id).Update(&Article{Name: "6"})
  364. assert.NoError(t, err)
  365. assert.EqualValues(t, 1, cnt)
  366. var s = "test"
  367. col1 := &UpdateAllCols{Ptr: &s}
  368. err = testEngine.Sync(col1)
  369. assert.NoError(t, err)
  370. _, err = testEngine.Insert(col1)
  371. assert.NoError(t, err)
  372. col2 := &UpdateAllCols{col1.Id, true, "", nil}
  373. _, err = testEngine.ID(col2.Id).AllCols().Update(col2)
  374. assert.NoError(t, err)
  375. col3 := &UpdateAllCols{}
  376. has, err = testEngine.ID(col2.Id).Get(col3)
  377. assert.NoError(t, err)
  378. assert.True(t, has)
  379. assert.EqualValues(t, *col2, *col3)
  380. {
  381. col1 := &UpdateMustCols{}
  382. err = testEngine.Sync(col1)
  383. if err != nil {
  384. t.Error(err)
  385. panic(err)
  386. }
  387. _, err = testEngine.Insert(col1)
  388. if err != nil {
  389. t.Error(err)
  390. panic(err)
  391. }
  392. col2 := &UpdateMustCols{col1.Id, true, ""}
  393. boolStr := testEngine.GetColumnMapper().Obj2Table("Bool")
  394. stringStr := testEngine.GetColumnMapper().Obj2Table("String")
  395. _, err = testEngine.ID(col2.Id).MustCols(boolStr, stringStr).Update(col2)
  396. if err != nil {
  397. t.Error(err)
  398. panic(err)
  399. }
  400. col3 := &UpdateMustCols{}
  401. has, err := testEngine.ID(col2.Id).Get(col3)
  402. assert.NoError(t, err)
  403. assert.True(t, has)
  404. assert.EqualValues(t, *col2, *col3)
  405. }
  406. }
  407. func TestUpdateIncrDecr(t *testing.T) {
  408. assert.NoError(t, prepareEngine())
  409. col1 := &UpdateIncr{
  410. Name: "test",
  411. }
  412. assert.NoError(t, testEngine.Sync(col1))
  413. _, err := testEngine.Insert(col1)
  414. assert.NoError(t, err)
  415. colName := testEngine.GetColumnMapper().Obj2Table("Cnt")
  416. cnt, err := testEngine.ID(col1.Id).Incr(colName).Update(col1)
  417. assert.NoError(t, err)
  418. assert.EqualValues(t, 1, cnt)
  419. newCol := new(UpdateIncr)
  420. has, err := testEngine.ID(col1.Id).Get(newCol)
  421. assert.NoError(t, err)
  422. assert.True(t, has)
  423. assert.EqualValues(t, 1, newCol.Cnt)
  424. cnt, err = testEngine.ID(col1.Id).Decr(colName).Update(col1)
  425. assert.NoError(t, err)
  426. assert.EqualValues(t, 1, cnt)
  427. newCol = new(UpdateIncr)
  428. has, err = testEngine.ID(col1.Id).Get(newCol)
  429. assert.NoError(t, err)
  430. assert.True(t, has)
  431. assert.EqualValues(t, 0, newCol.Cnt)
  432. cnt, err = testEngine.ID(col1.Id).Cols(colName).Incr(colName).Update(col1)
  433. assert.NoError(t, err)
  434. assert.EqualValues(t, 1, cnt)
  435. }
  436. type UpdatedUpdate struct {
  437. Id int64
  438. Updated time.Time `xorm:"updated"`
  439. }
  440. type UpdatedUpdate2 struct {
  441. Id int64
  442. Updated int64 `xorm:"updated"`
  443. }
  444. type UpdatedUpdate3 struct {
  445. Id int64
  446. Updated int `xorm:"updated bigint"`
  447. }
  448. type UpdatedUpdate4 struct {
  449. Id int64
  450. Updated int `xorm:"updated"`
  451. }
  452. type UpdatedUpdate5 struct {
  453. Id int64
  454. Updated time.Time `xorm:"updated bigint"`
  455. }
  456. func TestUpdateUpdated(t *testing.T) {
  457. assert.NoError(t, prepareEngine())
  458. di := new(UpdatedUpdate)
  459. err := testEngine.Sync2(di)
  460. if err != nil {
  461. t.Fatal(err)
  462. }
  463. _, err = testEngine.Insert(&UpdatedUpdate{})
  464. if err != nil {
  465. t.Fatal(err)
  466. }
  467. ci := &UpdatedUpdate{}
  468. _, err = testEngine.ID(1).Update(ci)
  469. if err != nil {
  470. t.Fatal(err)
  471. }
  472. has, err := testEngine.ID(1).Get(di)
  473. if err != nil {
  474. t.Fatal(err)
  475. }
  476. if !has {
  477. t.Fatal(ErrNotExist)
  478. }
  479. if ci.Updated.Unix() != di.Updated.Unix() {
  480. t.Fatal("should equal:", ci, di)
  481. }
  482. fmt.Println("ci:", ci, "di:", di)
  483. di2 := new(UpdatedUpdate2)
  484. err = testEngine.Sync2(di2)
  485. assert.NoError(t, err)
  486. now := time.Now()
  487. var di20 UpdatedUpdate2
  488. cnt, err := testEngine.Insert(&di20)
  489. assert.NoError(t, err)
  490. assert.EqualValues(t, 1, cnt)
  491. assert.True(t, now.Unix() <= di20.Updated)
  492. var di21 UpdatedUpdate2
  493. has, err = testEngine.ID(di20.Id).Get(&di21)
  494. assert.NoError(t, err)
  495. assert.True(t, has)
  496. assert.EqualValues(t, di20.Updated, di21.Updated)
  497. ci2 := &UpdatedUpdate2{}
  498. _, err = testEngine.ID(1).Update(ci2)
  499. assert.NoError(t, err)
  500. has, err = testEngine.ID(1).Get(di2)
  501. assert.NoError(t, err)
  502. assert.True(t, has)
  503. assert.EqualValues(t, ci2.Updated, di2.Updated)
  504. assert.True(t, ci2.Updated >= di21.Updated)
  505. di3 := new(UpdatedUpdate3)
  506. err = testEngine.Sync2(di3)
  507. if err != nil {
  508. t.Fatal(err)
  509. }
  510. _, err = testEngine.Insert(&UpdatedUpdate3{})
  511. if err != nil {
  512. t.Fatal(err)
  513. }
  514. ci3 := &UpdatedUpdate3{}
  515. _, err = testEngine.ID(1).Update(ci3)
  516. if err != nil {
  517. t.Fatal(err)
  518. }
  519. has, err = testEngine.ID(1).Get(di3)
  520. if err != nil {
  521. t.Fatal(err)
  522. }
  523. if !has {
  524. t.Fatal(ErrNotExist)
  525. }
  526. if ci3.Updated != di3.Updated {
  527. t.Fatal("should equal:", ci3, di3)
  528. }
  529. fmt.Println("ci3:", ci3, "di3:", di3)
  530. di4 := new(UpdatedUpdate4)
  531. err = testEngine.Sync2(di4)
  532. if err != nil {
  533. t.Fatal(err)
  534. }
  535. _, err = testEngine.Insert(&UpdatedUpdate4{})
  536. if err != nil {
  537. t.Fatal(err)
  538. }
  539. ci4 := &UpdatedUpdate4{}
  540. _, err = testEngine.ID(1).Update(ci4)
  541. if err != nil {
  542. t.Fatal(err)
  543. }
  544. has, err = testEngine.ID(1).Get(di4)
  545. if err != nil {
  546. t.Fatal(err)
  547. }
  548. if !has {
  549. t.Fatal(ErrNotExist)
  550. }
  551. if ci4.Updated != di4.Updated {
  552. t.Fatal("should equal:", ci4, di4)
  553. }
  554. fmt.Println("ci4:", ci4, "di4:", di4)
  555. di5 := new(UpdatedUpdate5)
  556. err = testEngine.Sync2(di5)
  557. if err != nil {
  558. t.Fatal(err)
  559. }
  560. _, err = testEngine.Insert(&UpdatedUpdate5{})
  561. if err != nil {
  562. t.Fatal(err)
  563. }
  564. ci5 := &UpdatedUpdate5{}
  565. _, err = testEngine.ID(1).Update(ci5)
  566. if err != nil {
  567. t.Fatal(err)
  568. }
  569. has, err = testEngine.ID(1).Get(di5)
  570. if err != nil {
  571. t.Fatal(err)
  572. }
  573. if !has {
  574. t.Fatal(ErrNotExist)
  575. }
  576. if ci5.Updated.Unix() != di5.Updated.Unix() {
  577. t.Fatal("should equal:", ci5, di5)
  578. }
  579. fmt.Println("ci5:", ci5, "di5:", di5)
  580. }
  581. func TestUpdateSameMapper(t *testing.T) {
  582. assert.NoError(t, prepareEngine())
  583. oldMapper := testEngine.GetTableMapper()
  584. testEngine.UnMapType(rValue(new(Userinfo)).Type())
  585. testEngine.UnMapType(rValue(new(Condi)).Type())
  586. testEngine.UnMapType(rValue(new(Article)).Type())
  587. testEngine.UnMapType(rValue(new(UpdateAllCols)).Type())
  588. testEngine.UnMapType(rValue(new(UpdateMustCols)).Type())
  589. testEngine.UnMapType(rValue(new(UpdateIncr)).Type())
  590. testEngine.SetMapper(core.SameMapper{})
  591. defer func() {
  592. testEngine.UnMapType(rValue(new(Userinfo)).Type())
  593. testEngine.UnMapType(rValue(new(Condi)).Type())
  594. testEngine.UnMapType(rValue(new(Article)).Type())
  595. testEngine.UnMapType(rValue(new(UpdateAllCols)).Type())
  596. testEngine.UnMapType(rValue(new(UpdateMustCols)).Type())
  597. testEngine.UnMapType(rValue(new(UpdateIncr)).Type())
  598. testEngine.SetMapper(oldMapper)
  599. }()
  600. assertSync(t, new(Userinfo))
  601. _, err := testEngine.Insert(&Userinfo{
  602. Username: "user1",
  603. })
  604. assert.NoError(t, err)
  605. var ori Userinfo
  606. has, err := testEngine.Get(&ori)
  607. assert.NoError(t, err)
  608. assert.True(t, has)
  609. // update by id
  610. user := Userinfo{Username: "xxx", Height: 1.2}
  611. cnt, err := testEngine.ID(ori.Uid).Update(&user)
  612. assert.NoError(t, err)
  613. assert.EqualValues(t, 1, cnt)
  614. condi := Condi{"Username": "zzz", "Departname": ""}
  615. cnt, err = testEngine.Table(&user).ID(ori.Uid).Update(&condi)
  616. assert.NoError(t, err)
  617. assert.EqualValues(t, 1, cnt)
  618. cnt, err = testEngine.Update(&Userinfo{Username: "yyy"}, &user)
  619. assert.NoError(t, err)
  620. total, err := testEngine.Count(&user)
  621. assert.NoError(t, err)
  622. assert.EqualValues(t, cnt, total)
  623. err = testEngine.Sync(&Article{})
  624. assert.NoError(t, err)
  625. defer func() {
  626. err = testEngine.DropTables(&Article{})
  627. assert.NoError(t, err)
  628. }()
  629. a := &Article{0, "1", "2", "3", "4", "5", 2}
  630. cnt, err = testEngine.Insert(a)
  631. assert.NoError(t, err)
  632. if cnt != 1 {
  633. err = errors.New(fmt.Sprintf("insert not returned 1 but %d", cnt))
  634. t.Error(err)
  635. panic(err)
  636. }
  637. if a.Id == 0 {
  638. err = errors.New("insert returned id is 0")
  639. t.Error(err)
  640. panic(err)
  641. }
  642. cnt, err = testEngine.ID(a.Id).Update(&Article{Name: "6"})
  643. assert.NoError(t, err)
  644. assert.EqualValues(t, 1, cnt)
  645. col1 := &UpdateAllCols{}
  646. err = testEngine.Sync(col1)
  647. assert.NoError(t, err)
  648. _, err = testEngine.Insert(col1)
  649. assert.NoError(t, err)
  650. col2 := &UpdateAllCols{col1.Id, true, "", nil}
  651. _, err = testEngine.ID(col2.Id).AllCols().Update(col2)
  652. assert.NoError(t, err)
  653. col3 := &UpdateAllCols{}
  654. has, err = testEngine.ID(col2.Id).Get(col3)
  655. assert.NoError(t, err)
  656. assert.True(t, has)
  657. assert.EqualValues(t, *col2, *col3)
  658. {
  659. col1 := &UpdateMustCols{}
  660. err = testEngine.Sync(col1)
  661. assert.NoError(t, err)
  662. _, err = testEngine.Insert(col1)
  663. assert.NoError(t, err)
  664. col2 := &UpdateMustCols{col1.Id, true, ""}
  665. boolStr := testEngine.GetColumnMapper().Obj2Table("Bool")
  666. stringStr := testEngine.GetColumnMapper().Obj2Table("String")
  667. _, err = testEngine.ID(col2.Id).MustCols(boolStr, stringStr).Update(col2)
  668. assert.NoError(t, err)
  669. col3 := &UpdateMustCols{}
  670. has, err := testEngine.ID(col2.Id).Get(col3)
  671. assert.NoError(t, err)
  672. assert.True(t, has)
  673. assert.EqualValues(t, *col2, *col3)
  674. }
  675. {
  676. col1 := &UpdateIncr{}
  677. err = testEngine.Sync(col1)
  678. if err != nil {
  679. t.Error(err)
  680. panic(err)
  681. }
  682. _, err = testEngine.Insert(col1)
  683. if err != nil {
  684. t.Error(err)
  685. panic(err)
  686. }
  687. cnt, err := testEngine.ID(col1.Id).Incr("`Cnt`").Update(col1)
  688. if err != nil {
  689. t.Error(err)
  690. panic(err)
  691. }
  692. if cnt != 1 {
  693. err = errors.New("update incr failed")
  694. t.Error(err)
  695. panic(err)
  696. }
  697. newCol := new(UpdateIncr)
  698. has, err := testEngine.ID(col1.Id).Get(newCol)
  699. if err != nil {
  700. t.Error(err)
  701. panic(err)
  702. }
  703. if !has {
  704. err = errors.New("has incr failed")
  705. t.Error(err)
  706. panic(err)
  707. }
  708. if 1 != newCol.Cnt {
  709. err = errors.New("incr failed")
  710. t.Error(err)
  711. panic(err)
  712. }
  713. }
  714. }
  715. func TestUseBool(t *testing.T) {
  716. assert.NoError(t, prepareEngine())
  717. assertSync(t, new(Userinfo))
  718. cnt1, err := testEngine.Count(&Userinfo{})
  719. if err != nil {
  720. t.Error(err)
  721. panic(err)
  722. }
  723. users := make([]Userinfo, 0)
  724. err = testEngine.Find(&users)
  725. if err != nil {
  726. t.Error(err)
  727. panic(err)
  728. }
  729. var fNumber int64
  730. for _, u := range users {
  731. if u.IsMan == false {
  732. fNumber += 1
  733. }
  734. }
  735. cnt2, err := testEngine.UseBool().Update(&Userinfo{IsMan: true})
  736. if err != nil {
  737. t.Error(err)
  738. panic(err)
  739. }
  740. if fNumber != cnt2 {
  741. fmt.Println("cnt1", cnt1, "fNumber", fNumber, "cnt2", cnt2)
  742. /*err = errors.New("Updated number is not corrected.")
  743. t.Error(err)
  744. panic(err)*/
  745. }
  746. _, err = testEngine.Update(&Userinfo{IsMan: true})
  747. if err == nil {
  748. err = errors.New("error condition")
  749. t.Error(err)
  750. panic(err)
  751. }
  752. }
  753. func TestBool(t *testing.T) {
  754. assert.NoError(t, prepareEngine())
  755. assertSync(t, new(Userinfo))
  756. _, err := testEngine.UseBool().Update(&Userinfo{IsMan: true})
  757. if err != nil {
  758. t.Error(err)
  759. panic(err)
  760. }
  761. users := make([]Userinfo, 0)
  762. err = testEngine.Find(&users)
  763. if err != nil {
  764. t.Error(err)
  765. panic(err)
  766. }
  767. for _, user := range users {
  768. if !user.IsMan {
  769. err = errors.New("update bool or find bool error")
  770. t.Error(err)
  771. panic(err)
  772. }
  773. }
  774. _, err = testEngine.UseBool().Update(&Userinfo{IsMan: false})
  775. if err != nil {
  776. t.Error(err)
  777. panic(err)
  778. }
  779. users = make([]Userinfo, 0)
  780. err = testEngine.Find(&users)
  781. if err != nil {
  782. t.Error(err)
  783. panic(err)
  784. }
  785. for _, user := range users {
  786. if user.IsMan {
  787. err = errors.New("update bool or find bool error")
  788. t.Error(err)
  789. panic(err)
  790. }
  791. }
  792. }
  793. func TestNoUpdate(t *testing.T) {
  794. assert.NoError(t, prepareEngine())
  795. type NoUpdate struct {
  796. Id int64
  797. Content string
  798. }
  799. assertSync(t, new(NoUpdate))
  800. cnt, err := testEngine.Insert(&NoUpdate{
  801. Content: "test",
  802. })
  803. assert.NoError(t, err)
  804. assert.EqualValues(t, 1, cnt)
  805. _, err = testEngine.ID(1).Update(&NoUpdate{})
  806. assert.Error(t, err)
  807. assert.EqualValues(t, "No content found to be updated", err.Error())
  808. }
  809. func TestNewUpdate(t *testing.T) {
  810. assert.NoError(t, prepareEngine())
  811. type TbUserInfo struct {
  812. Id int64 `xorm:"pk autoincr unique BIGINT" json:"id"`
  813. Phone string `xorm:"not null unique VARCHAR(20)" json:"phone"`
  814. UserName string `xorm:"VARCHAR(20)" json:"user_name"`
  815. Gender int `xorm:"default 0 INTEGER" json:"gender"`
  816. Pw string `xorm:"VARCHAR(100)" json:"pw"`
  817. Token string `xorm:"TEXT" json:"token"`
  818. Avatar string `xorm:"TEXT" json:"avatar"`
  819. Extras interface{} `xorm:"JSON" json:"extras"`
  820. Created time.Time `xorm:"DATETIME created"`
  821. Updated time.Time `xorm:"DATETIME updated"`
  822. Deleted time.Time `xorm:"DATETIME deleted"`
  823. }
  824. assertSync(t, new(TbUserInfo))
  825. targetUsr := TbUserInfo{Phone: "13126564922"}
  826. changeUsr := TbUserInfo{Token: "ABCDEFG"}
  827. af, err := testEngine.Update(&changeUsr, &targetUsr)
  828. assert.NoError(t, err)
  829. assert.EqualValues(t, 0, af)
  830. af, err = testEngine.Table(new(TbUserInfo)).Where("phone=?", 13126564922).Update(&changeUsr)
  831. assert.NoError(t, err)
  832. assert.EqualValues(t, 0, af)
  833. }
  834. func TestUpdateUpdate(t *testing.T) {
  835. assert.NoError(t, prepareEngine())
  836. type PublicKeyUpdate struct {
  837. Id int64
  838. UpdatedUnix int64 `xorm:"updated"`
  839. }
  840. assertSync(t, new(PublicKeyUpdate))
  841. cnt, err := testEngine.ID(1).Cols("updated_unix").Update(&PublicKeyUpdate{
  842. UpdatedUnix: time.Now().Unix(),
  843. })
  844. assert.NoError(t, err)
  845. assert.EqualValues(t, 0, cnt)
  846. }
  847. func TestCreatedUpdated2(t *testing.T) {
  848. assert.NoError(t, prepareEngine())
  849. type CreatedUpdatedStruct struct {
  850. Id int64
  851. Name string
  852. CreateAt time.Time `xorm:"created" json:"create_at"`
  853. UpdateAt time.Time `xorm:"updated" json:"update_at"`
  854. }
  855. assertSync(t, new(CreatedUpdatedStruct))
  856. var s = CreatedUpdatedStruct{
  857. Name: "test",
  858. }
  859. cnt, err := testEngine.Insert(&s)
  860. assert.NoError(t, err)
  861. assert.EqualValues(t, 1, cnt)
  862. assert.EqualValues(t, s.UpdateAt.Unix(), s.CreateAt.Unix())
  863. time.Sleep(time.Second)
  864. var s1 = CreatedUpdatedStruct{
  865. Name: "test1",
  866. CreateAt: s.CreateAt,
  867. UpdateAt: s.UpdateAt,
  868. }
  869. cnt, err = testEngine.ID(1).Update(&s1)
  870. assert.NoError(t, err)
  871. assert.EqualValues(t, 1, cnt)
  872. assert.EqualValues(t, s.CreateAt.Unix(), s1.CreateAt.Unix())
  873. assert.True(t, s1.UpdateAt.Unix() > s.UpdateAt.Unix())
  874. var s2 CreatedUpdatedStruct
  875. has, err := testEngine.ID(1).Get(&s2)
  876. assert.NoError(t, err)
  877. assert.True(t, has)
  878. assert.EqualValues(t, s.CreateAt.Unix(), s2.CreateAt.Unix())
  879. assert.True(t, s2.UpdateAt.Unix() > s.UpdateAt.Unix())
  880. assert.True(t, s2.UpdateAt.Unix() > s2.CreateAt.Unix())
  881. }
  882. func TestDeletedUpdate(t *testing.T) {
  883. assert.NoError(t, prepareEngine())
  884. type DeletedUpdatedStruct struct {
  885. Id int64
  886. Name string
  887. DeletedAt time.Time `xorm:"deleted"`
  888. }
  889. assertSync(t, new(DeletedUpdatedStruct))
  890. var s = DeletedUpdatedStruct{
  891. Name: "test",
  892. }
  893. cnt, err := testEngine.Insert(&s)
  894. assert.NoError(t, err)
  895. assert.EqualValues(t, 1, cnt)
  896. cnt, err = testEngine.ID(s.Id).Delete(&DeletedUpdatedStruct{})
  897. assert.NoError(t, err)
  898. assert.EqualValues(t, 1, cnt)
  899. s.DeletedAt = time.Time{}
  900. cnt, err = testEngine.Unscoped().Nullable("deleted_at").Update(&s)
  901. assert.NoError(t, err)
  902. assert.EqualValues(t, 1, cnt)
  903. var s1 DeletedUpdatedStruct
  904. has, err := testEngine.ID(s.Id).Get(&s1)
  905. assert.EqualValues(t, true, has)
  906. cnt, err = testEngine.ID(s.Id).Delete(&DeletedUpdatedStruct{})
  907. assert.NoError(t, err)
  908. assert.EqualValues(t, 1, cnt)
  909. cnt, err = testEngine.ID(s.Id).Cols("deleted_at").Update(&DeletedUpdatedStruct{})
  910. assert.EqualValues(t, "No content found to be updated", err.Error())
  911. assert.EqualValues(t, 0, cnt)
  912. cnt, err = testEngine.ID(s.Id).Unscoped().Cols("deleted_at").Update(&DeletedUpdatedStruct{})
  913. assert.NoError(t, err)
  914. assert.EqualValues(t, 1, cnt)
  915. var s2 DeletedUpdatedStruct
  916. has, err = testEngine.ID(s.Id).Get(&s2)
  917. assert.EqualValues(t, true, has)
  918. }
  919. func TestUpdateMapCondition(t *testing.T) {
  920. assert.NoError(t, prepareEngine())
  921. type UpdateMapCondition struct {
  922. Id int64
  923. String string
  924. }
  925. assertSync(t, new(UpdateMapCondition))
  926. var c = UpdateMapCondition{
  927. String: "string",
  928. }
  929. _, err := testEngine.Insert(&c)
  930. assert.NoError(t, err)
  931. cnt, err := testEngine.Update(&UpdateMapCondition{
  932. String: "string1",
  933. }, map[string]interface{}{
  934. "id": c.Id,
  935. })
  936. assert.NoError(t, err)
  937. assert.EqualValues(t, 1, cnt)
  938. var c2 UpdateMapCondition
  939. has, err := testEngine.ID(c.Id).Get(&c2)
  940. assert.NoError(t, err)
  941. assert.True(t, has)
  942. assert.EqualValues(t, "string1", c2.String)
  943. }
  944. func TestUpdateMapContent(t *testing.T) {
  945. assert.NoError(t, prepareEngine())
  946. type UpdateMapContent struct {
  947. Id int64
  948. Name string
  949. IsMan bool
  950. Age int
  951. Gender int // 1 is man, 2 is woman
  952. }
  953. assertSync(t, new(UpdateMapContent))
  954. var c = UpdateMapContent{
  955. Name: "lunny",
  956. IsMan: true,
  957. Gender: 1,
  958. Age: 18,
  959. }
  960. _, err := testEngine.Insert(&c)
  961. assert.NoError(t, err)
  962. assert.EqualValues(t, 18, c.Age)
  963. cnt, err := testEngine.Table(new(UpdateMapContent)).ID(c.Id).Update(map[string]interface{}{"age": 0})
  964. assert.NoError(t, err)
  965. assert.EqualValues(t, 1, cnt)
  966. var c1 UpdateMapContent
  967. has, err := testEngine.ID(c.Id).Get(&c1)
  968. assert.NoError(t, err)
  969. assert.True(t, has)
  970. assert.EqualValues(t, 0, c1.Age)
  971. cnt, err = testEngine.Table(new(UpdateMapContent)).ID(c.Id).Update(map[string]interface{}{
  972. "age": 16,
  973. "is_man": false,
  974. "gender": 2,
  975. })
  976. assert.NoError(t, err)
  977. assert.EqualValues(t, 1, cnt)
  978. var c2 UpdateMapContent
  979. has, err = testEngine.ID(c.Id).Get(&c2)
  980. assert.NoError(t, err)
  981. assert.True(t, has)
  982. assert.EqualValues(t, 16, c2.Age)
  983. assert.EqualValues(t, false, c2.IsMan)
  984. assert.EqualValues(t, 2, c2.Gender)
  985. cnt, err = testEngine.Table(testEngine.TableName(new(UpdateMapContent))).ID(c.Id).Update(map[string]interface{}{
  986. "age": 15,
  987. "is_man": true,
  988. "gender": 1,
  989. })
  990. assert.NoError(t, err)
  991. assert.EqualValues(t, 1, cnt)
  992. var c3 UpdateMapContent
  993. has, err = testEngine.ID(c.Id).Get(&c3)
  994. assert.NoError(t, err)
  995. assert.True(t, has)
  996. assert.EqualValues(t, 15, c3.Age)
  997. assert.EqualValues(t, true, c3.IsMan)
  998. assert.EqualValues(t, 1, c3.Gender)
  999. }
  1000. func TestUpdateCondiBean(t *testing.T) {
  1001. type NeedUpdateBean struct {
  1002. Id int64
  1003. Name string
  1004. }
  1005. type NeedUpdateCondiBean struct {
  1006. Name string
  1007. }
  1008. assert.NoError(t, prepareEngine())
  1009. assertSync(t, new(NeedUpdateBean))
  1010. cnt, err := testEngine.Insert(&NeedUpdateBean{
  1011. Name: "name1",
  1012. })
  1013. assert.NoError(t, err)
  1014. assert.EqualValues(t, 1, cnt)
  1015. has, err := testEngine.Exist(&NeedUpdateBean{
  1016. Name: "name1",
  1017. })
  1018. assert.NoError(t, err)
  1019. assert.True(t, has)
  1020. cnt, err = testEngine.Update(&NeedUpdateBean{
  1021. Name: "name2",
  1022. }, &NeedUpdateCondiBean{
  1023. Name: "name1",
  1024. })
  1025. assert.NoError(t, err)
  1026. assert.EqualValues(t, 1, cnt)
  1027. has, err = testEngine.Exist(&NeedUpdateBean{
  1028. Name: "name2",
  1029. })
  1030. assert.NoError(t, err)
  1031. assert.True(t, has)
  1032. cnt, err = testEngine.Update(&NeedUpdateBean{
  1033. Name: "name1",
  1034. }, NeedUpdateCondiBean{
  1035. Name: "name2",
  1036. })
  1037. assert.NoError(t, err)
  1038. assert.EqualValues(t, 1, cnt)
  1039. has, err = testEngine.Exist(&NeedUpdateBean{
  1040. Name: "name1",
  1041. })
  1042. assert.NoError(t, err)
  1043. assert.True(t, has)
  1044. }
  1045. func TestWhereCondErrorWhenUpdate(t *testing.T) {
  1046. type AuthRequestError struct {
  1047. ChallengeToken string
  1048. RequestToken string
  1049. }
  1050. assert.NoError(t, prepareEngine())
  1051. assertSync(t, new(AuthRequestError))
  1052. _, err := testEngine.Cols("challenge_token", "request_token", "challenge_agent", "status").
  1053. Where(&AuthRequestError{ChallengeToken: "1"}).
  1054. Update(&AuthRequestError{
  1055. ChallengeToken: "2",
  1056. })
  1057. assert.Error(t, err)
  1058. assert.EqualValues(t, ErrConditionType, err)
  1059. }
  1060. func TestUpdateDeleted(t *testing.T) {
  1061. assert.NoError(t, prepareEngine())
  1062. type UpdateDeletedStruct struct {
  1063. Id int64
  1064. Name string
  1065. DeletedAt time.Time `xorm:"deleted"`
  1066. }
  1067. assertSync(t, new(UpdateDeletedStruct))
  1068. var s = UpdateDeletedStruct{
  1069. Name: "test",
  1070. }
  1071. cnt, err := testEngine.Insert(&s)
  1072. assert.NoError(t, err)
  1073. assert.EqualValues(t, 1, cnt)
  1074. cnt, err = testEngine.ID(s.Id).Delete(&UpdateDeletedStruct{})
  1075. assert.NoError(t, err)
  1076. assert.EqualValues(t, 1, cnt)
  1077. cnt, err = testEngine.ID(s.Id).Update(&UpdateDeletedStruct{
  1078. Name: "test1",
  1079. })
  1080. assert.NoError(t, err)
  1081. assert.EqualValues(t, 0, cnt)
  1082. cnt, err = testEngine.Table(&UpdateDeletedStruct{}).ID(s.Id).Update(map[string]interface{}{
  1083. "name": "test1",
  1084. })
  1085. assert.NoError(t, err)
  1086. assert.EqualValues(t, 0, cnt)
  1087. cnt, err = testEngine.ID(s.Id).Unscoped().Update(&UpdateDeletedStruct{
  1088. Name: "test1",
  1089. })
  1090. assert.NoError(t, err)
  1091. assert.EqualValues(t, 1, cnt)
  1092. }
  1093. func TestUpdateExprs(t *testing.T) {
  1094. assert.NoError(t, prepareEngine())
  1095. type UpdateExprs struct {
  1096. Id int64
  1097. NumIssues int
  1098. Name string
  1099. }
  1100. assertSync(t, new(UpdateExprs))
  1101. _, err := testEngine.Insert(&UpdateExprs{
  1102. NumIssues: 1,
  1103. Name: "lunny",
  1104. })
  1105. assert.NoError(t, err)
  1106. _, err = testEngine.SetExpr("num_issues", "num_issues+1").AllCols().Update(&UpdateExprs{
  1107. NumIssues: 3,
  1108. Name: "lunny xiao",
  1109. })
  1110. assert.NoError(t, err)
  1111. var ue UpdateExprs
  1112. has, err := testEngine.Get(&ue)
  1113. assert.NoError(t, err)
  1114. assert.True(t, has)
  1115. assert.EqualValues(t, 2, ue.NumIssues)
  1116. assert.EqualValues(t, "lunny xiao", ue.Name)
  1117. }
  1118. func TestUpdateAlias(t *testing.T) {
  1119. assert.NoError(t, prepareEngine())
  1120. type UpdateAlias struct {
  1121. Id int64
  1122. NumIssues int
  1123. Name string
  1124. }
  1125. assertSync(t, new(UpdateAlias))
  1126. _, err := testEngine.Insert(&UpdateAlias{
  1127. NumIssues: 1,
  1128. Name: "lunny",
  1129. })
  1130. assert.NoError(t, err)
  1131. _, err = testEngine.Alias("ua").Where("ua.id = ?", 1).Update(&UpdateAlias{
  1132. NumIssues: 2,
  1133. Name: "lunny xiao",
  1134. })
  1135. assert.NoError(t, err)
  1136. var ue UpdateAlias
  1137. has, err := testEngine.Get(&ue)
  1138. assert.NoError(t, err)
  1139. assert.True(t, has)
  1140. assert.EqualValues(t, 2, ue.NumIssues)
  1141. assert.EqualValues(t, "lunny xiao", ue.Name)
  1142. }