THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

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.

1424 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. if err != nil {
  259. t.Error(err)
  260. panic(err)
  261. }
  262. if cnt != 1 {
  263. err = errors.New("update not returned 1")
  264. t.Error(err)
  265. panic(err)
  266. return
  267. }
  268. condi := Condi{"username": "zzz", "departname": ""}
  269. cnt, err = testEngine.Table(&user).ID(ori.Uid).Update(&condi)
  270. if err != nil {
  271. t.Error(err)
  272. panic(err)
  273. }
  274. if cnt != 1 {
  275. err = errors.New("update not returned 1")
  276. t.Error(err)
  277. panic(err)
  278. return
  279. }
  280. cnt, err = testEngine.Update(&Userinfo{Username: "yyy"}, &user)
  281. if err != nil {
  282. t.Error(err)
  283. panic(err)
  284. }
  285. total, err := testEngine.Count(&user)
  286. if err != nil {
  287. t.Error(err)
  288. panic(err)
  289. }
  290. if cnt != total {
  291. err = errors.New("insert not returned 1")
  292. t.Error(err)
  293. panic(err)
  294. return
  295. }
  296. // nullable update
  297. {
  298. user := &Userinfo{Username: "not null data", Height: 180.5}
  299. _, err := testEngine.Insert(user)
  300. if err != nil {
  301. t.Error(err)
  302. panic(err)
  303. }
  304. userID := user.Uid
  305. has, err := testEngine.ID(userID).
  306. And("username = ?", user.Username).
  307. And("height = ?", user.Height).
  308. And("departname = ?", "").
  309. And("detail_id = ?", 0).
  310. And("is_man = ?", 0).
  311. Get(&Userinfo{})
  312. if err != nil {
  313. t.Error(err)
  314. panic(err)
  315. }
  316. if !has {
  317. err = errors.New("cannot insert properly")
  318. t.Error(err)
  319. panic(err)
  320. }
  321. updatedUser := &Userinfo{Username: "null data"}
  322. cnt, err = testEngine.ID(userID).
  323. Nullable("height", "departname", "is_man", "created").
  324. Update(updatedUser)
  325. if err != nil {
  326. t.Error(err)
  327. panic(err)
  328. }
  329. if cnt != 1 {
  330. err = errors.New("update not returned 1")
  331. t.Error(err)
  332. panic(err)
  333. }
  334. has, err = testEngine.ID(userID).
  335. And("username = ?", updatedUser.Username).
  336. And("height IS NULL").
  337. And("departname IS NULL").
  338. And("is_man IS NULL").
  339. And("created IS NULL").
  340. And("detail_id = ?", 0).
  341. Get(&Userinfo{})
  342. if err != nil {
  343. t.Error(err)
  344. panic(err)
  345. }
  346. if !has {
  347. err = errors.New("cannot update with null properly")
  348. t.Error(err)
  349. panic(err)
  350. }
  351. cnt, err = testEngine.ID(userID).Delete(&Userinfo{})
  352. if err != nil {
  353. t.Error(err)
  354. panic(err)
  355. }
  356. if cnt != 1 {
  357. err = errors.New("delete not returned 1")
  358. t.Error(err)
  359. panic(err)
  360. }
  361. }
  362. err = testEngine.StoreEngine("Innodb").Sync2(&Article{})
  363. if err != nil {
  364. t.Error(err)
  365. panic(err)
  366. }
  367. defer func() {
  368. err = testEngine.DropTables(&Article{})
  369. if err != nil {
  370. t.Error(err)
  371. panic(err)
  372. }
  373. }()
  374. a := &Article{0, "1", "2", "3", "4", "5", 2}
  375. cnt, err = testEngine.Insert(a)
  376. if err != nil {
  377. t.Error(err)
  378. panic(err)
  379. }
  380. if cnt != 1 {
  381. err = errors.New(fmt.Sprintf("insert not returned 1 but %d", cnt))
  382. t.Error(err)
  383. panic(err)
  384. }
  385. if a.Id == 0 {
  386. err = errors.New("insert returned id is 0")
  387. t.Error(err)
  388. panic(err)
  389. }
  390. cnt, err = testEngine.ID(a.Id).Update(&Article{Name: "6"})
  391. if err != nil {
  392. t.Error(err)
  393. panic(err)
  394. }
  395. if cnt != 1 {
  396. err = errors.New(fmt.Sprintf("insert not returned 1 but %d", cnt))
  397. t.Error(err)
  398. panic(err)
  399. return
  400. }
  401. var s = "test"
  402. col1 := &UpdateAllCols{Ptr: &s}
  403. err = testEngine.Sync(col1)
  404. assert.NoError(t, err)
  405. _, err = testEngine.Insert(col1)
  406. assert.NoError(t, err)
  407. col2 := &UpdateAllCols{col1.Id, true, "", nil}
  408. _, err = testEngine.ID(col2.Id).AllCols().Update(col2)
  409. assert.NoError(t, err)
  410. col3 := &UpdateAllCols{}
  411. has, err = testEngine.ID(col2.Id).Get(col3)
  412. assert.NoError(t, err)
  413. if !has {
  414. err = errors.New(fmt.Sprintf("cannot get id %d", col2.Id))
  415. t.Error(err)
  416. panic(err)
  417. return
  418. }
  419. if *col2 != *col3 {
  420. err = errors.New(fmt.Sprintf("col2 should eq col3"))
  421. t.Error(err)
  422. panic(err)
  423. return
  424. }
  425. {
  426. col1 := &UpdateMustCols{}
  427. err = testEngine.Sync(col1)
  428. if err != nil {
  429. t.Error(err)
  430. panic(err)
  431. }
  432. _, err = testEngine.Insert(col1)
  433. if err != nil {
  434. t.Error(err)
  435. panic(err)
  436. }
  437. col2 := &UpdateMustCols{col1.Id, true, ""}
  438. boolStr := testEngine.GetColumnMapper().Obj2Table("Bool")
  439. stringStr := testEngine.GetColumnMapper().Obj2Table("String")
  440. _, err = testEngine.ID(col2.Id).MustCols(boolStr, stringStr).Update(col2)
  441. if err != nil {
  442. t.Error(err)
  443. panic(err)
  444. }
  445. col3 := &UpdateMustCols{}
  446. has, err := testEngine.ID(col2.Id).Get(col3)
  447. if err != nil {
  448. t.Error(err)
  449. panic(err)
  450. }
  451. if !has {
  452. err = errors.New(fmt.Sprintf("cannot get id %d", col2.Id))
  453. t.Error(err)
  454. panic(err)
  455. return
  456. }
  457. if *col2 != *col3 {
  458. err = errors.New(fmt.Sprintf("col2 should eq col3"))
  459. t.Error(err)
  460. panic(err)
  461. return
  462. }
  463. }
  464. }
  465. func TestUpdateIncrDecr(t *testing.T) {
  466. assert.NoError(t, prepareEngine())
  467. col1 := &UpdateIncr{
  468. Name: "test",
  469. }
  470. assert.NoError(t, testEngine.Sync(col1))
  471. _, err := testEngine.Insert(col1)
  472. assert.NoError(t, err)
  473. colName := testEngine.GetColumnMapper().Obj2Table("Cnt")
  474. cnt, err := testEngine.ID(col1.Id).Incr(colName).Update(col1)
  475. assert.NoError(t, err)
  476. assert.EqualValues(t, 1, cnt)
  477. newCol := new(UpdateIncr)
  478. has, err := testEngine.ID(col1.Id).Get(newCol)
  479. assert.NoError(t, err)
  480. assert.True(t, has)
  481. assert.EqualValues(t, 1, newCol.Cnt)
  482. cnt, err = testEngine.ID(col1.Id).Decr(colName).Update(col1)
  483. assert.NoError(t, err)
  484. assert.EqualValues(t, 1, cnt)
  485. newCol = new(UpdateIncr)
  486. has, err = testEngine.ID(col1.Id).Get(newCol)
  487. assert.NoError(t, err)
  488. assert.True(t, has)
  489. assert.EqualValues(t, 0, newCol.Cnt)
  490. cnt, err = testEngine.ID(col1.Id).Cols(colName).Incr(colName).Update(col1)
  491. assert.NoError(t, err)
  492. assert.EqualValues(t, 1, cnt)
  493. }
  494. type UpdatedUpdate struct {
  495. Id int64
  496. Updated time.Time `xorm:"updated"`
  497. }
  498. type UpdatedUpdate2 struct {
  499. Id int64
  500. Updated int64 `xorm:"updated"`
  501. }
  502. type UpdatedUpdate3 struct {
  503. Id int64
  504. Updated int `xorm:"updated bigint"`
  505. }
  506. type UpdatedUpdate4 struct {
  507. Id int64
  508. Updated int `xorm:"updated"`
  509. }
  510. type UpdatedUpdate5 struct {
  511. Id int64
  512. Updated time.Time `xorm:"updated bigint"`
  513. }
  514. func TestUpdateUpdated(t *testing.T) {
  515. assert.NoError(t, prepareEngine())
  516. di := new(UpdatedUpdate)
  517. err := testEngine.Sync2(di)
  518. if err != nil {
  519. t.Fatal(err)
  520. }
  521. _, err = testEngine.Insert(&UpdatedUpdate{})
  522. if err != nil {
  523. t.Fatal(err)
  524. }
  525. ci := &UpdatedUpdate{}
  526. _, err = testEngine.ID(1).Update(ci)
  527. if err != nil {
  528. t.Fatal(err)
  529. }
  530. has, err := testEngine.ID(1).Get(di)
  531. if err != nil {
  532. t.Fatal(err)
  533. }
  534. if !has {
  535. t.Fatal(ErrNotExist)
  536. }
  537. if ci.Updated.Unix() != di.Updated.Unix() {
  538. t.Fatal("should equal:", ci, di)
  539. }
  540. fmt.Println("ci:", ci, "di:", di)
  541. di2 := new(UpdatedUpdate2)
  542. err = testEngine.Sync2(di2)
  543. assert.NoError(t, err)
  544. now := time.Now()
  545. var di20 UpdatedUpdate2
  546. cnt, err := testEngine.Insert(&di20)
  547. assert.NoError(t, err)
  548. assert.EqualValues(t, 1, cnt)
  549. assert.True(t, now.Unix() <= di20.Updated)
  550. var di21 UpdatedUpdate2
  551. has, err = testEngine.ID(di20.Id).Get(&di21)
  552. assert.NoError(t, err)
  553. assert.True(t, has)
  554. assert.EqualValues(t, di20.Updated, di21.Updated)
  555. ci2 := &UpdatedUpdate2{}
  556. _, err = testEngine.ID(1).Update(ci2)
  557. assert.NoError(t, err)
  558. has, err = testEngine.ID(1).Get(di2)
  559. assert.NoError(t, err)
  560. assert.True(t, has)
  561. assert.EqualValues(t, ci2.Updated, di2.Updated)
  562. assert.True(t, ci2.Updated >= di21.Updated)
  563. di3 := new(UpdatedUpdate3)
  564. err = testEngine.Sync2(di3)
  565. if err != nil {
  566. t.Fatal(err)
  567. }
  568. _, err = testEngine.Insert(&UpdatedUpdate3{})
  569. if err != nil {
  570. t.Fatal(err)
  571. }
  572. ci3 := &UpdatedUpdate3{}
  573. _, err = testEngine.ID(1).Update(ci3)
  574. if err != nil {
  575. t.Fatal(err)
  576. }
  577. has, err = testEngine.ID(1).Get(di3)
  578. if err != nil {
  579. t.Fatal(err)
  580. }
  581. if !has {
  582. t.Fatal(ErrNotExist)
  583. }
  584. if ci3.Updated != di3.Updated {
  585. t.Fatal("should equal:", ci3, di3)
  586. }
  587. fmt.Println("ci3:", ci3, "di3:", di3)
  588. di4 := new(UpdatedUpdate4)
  589. err = testEngine.Sync2(di4)
  590. if err != nil {
  591. t.Fatal(err)
  592. }
  593. _, err = testEngine.Insert(&UpdatedUpdate4{})
  594. if err != nil {
  595. t.Fatal(err)
  596. }
  597. ci4 := &UpdatedUpdate4{}
  598. _, err = testEngine.ID(1).Update(ci4)
  599. if err != nil {
  600. t.Fatal(err)
  601. }
  602. has, err = testEngine.ID(1).Get(di4)
  603. if err != nil {
  604. t.Fatal(err)
  605. }
  606. if !has {
  607. t.Fatal(ErrNotExist)
  608. }
  609. if ci4.Updated != di4.Updated {
  610. t.Fatal("should equal:", ci4, di4)
  611. }
  612. fmt.Println("ci4:", ci4, "di4:", di4)
  613. di5 := new(UpdatedUpdate5)
  614. err = testEngine.Sync2(di5)
  615. if err != nil {
  616. t.Fatal(err)
  617. }
  618. _, err = testEngine.Insert(&UpdatedUpdate5{})
  619. if err != nil {
  620. t.Fatal(err)
  621. }
  622. ci5 := &UpdatedUpdate5{}
  623. _, err = testEngine.ID(1).Update(ci5)
  624. if err != nil {
  625. t.Fatal(err)
  626. }
  627. has, err = testEngine.ID(1).Get(di5)
  628. if err != nil {
  629. t.Fatal(err)
  630. }
  631. if !has {
  632. t.Fatal(ErrNotExist)
  633. }
  634. if ci5.Updated.Unix() != di5.Updated.Unix() {
  635. t.Fatal("should equal:", ci5, di5)
  636. }
  637. fmt.Println("ci5:", ci5, "di5:", di5)
  638. }
  639. func TestUpdateSameMapper(t *testing.T) {
  640. assert.NoError(t, prepareEngine())
  641. oldMapper := testEngine.GetTableMapper()
  642. testEngine.UnMapType(rValue(new(Userinfo)).Type())
  643. testEngine.UnMapType(rValue(new(Condi)).Type())
  644. testEngine.UnMapType(rValue(new(Article)).Type())
  645. testEngine.UnMapType(rValue(new(UpdateAllCols)).Type())
  646. testEngine.UnMapType(rValue(new(UpdateMustCols)).Type())
  647. testEngine.UnMapType(rValue(new(UpdateIncr)).Type())
  648. testEngine.SetMapper(core.SameMapper{})
  649. defer func() {
  650. testEngine.UnMapType(rValue(new(Userinfo)).Type())
  651. testEngine.UnMapType(rValue(new(Condi)).Type())
  652. testEngine.UnMapType(rValue(new(Article)).Type())
  653. testEngine.UnMapType(rValue(new(UpdateAllCols)).Type())
  654. testEngine.UnMapType(rValue(new(UpdateMustCols)).Type())
  655. testEngine.UnMapType(rValue(new(UpdateIncr)).Type())
  656. testEngine.SetMapper(oldMapper)
  657. }()
  658. assertSync(t, new(Userinfo))
  659. _, err := testEngine.Insert(&Userinfo{
  660. Username: "user1",
  661. })
  662. assert.NoError(t, err)
  663. var ori Userinfo
  664. has, err := testEngine.Get(&ori)
  665. assert.NoError(t, err)
  666. assert.True(t, has)
  667. // update by id
  668. user := Userinfo{Username: "xxx", Height: 1.2}
  669. cnt, err := testEngine.ID(ori.Uid).Update(&user)
  670. assert.NoError(t, err)
  671. assert.EqualValues(t, 1, cnt)
  672. condi := Condi{"Username": "zzz", "Departname": ""}
  673. cnt, err = testEngine.Table(&user).ID(ori.Uid).Update(&condi)
  674. assert.NoError(t, err)
  675. assert.EqualValues(t, 1, cnt)
  676. cnt, err = testEngine.Update(&Userinfo{Username: "yyy"}, &user)
  677. assert.NoError(t, err)
  678. total, err := testEngine.Count(&user)
  679. assert.NoError(t, err)
  680. assert.EqualValues(t, cnt, total)
  681. err = testEngine.Sync(&Article{})
  682. assert.NoError(t, err)
  683. defer func() {
  684. err = testEngine.DropTables(&Article{})
  685. assert.NoError(t, err)
  686. }()
  687. a := &Article{0, "1", "2", "3", "4", "5", 2}
  688. cnt, err = testEngine.Insert(a)
  689. assert.NoError(t, err)
  690. if cnt != 1 {
  691. err = errors.New(fmt.Sprintf("insert not returned 1 but %d", cnt))
  692. t.Error(err)
  693. panic(err)
  694. }
  695. if a.Id == 0 {
  696. err = errors.New("insert returned id is 0")
  697. t.Error(err)
  698. panic(err)
  699. }
  700. cnt, err = testEngine.ID(a.Id).Update(&Article{Name: "6"})
  701. assert.NoError(t, err)
  702. if cnt != 1 {
  703. err = errors.New(fmt.Sprintf("insert not returned 1 but %d", cnt))
  704. t.Error(err)
  705. panic(err)
  706. return
  707. }
  708. col1 := &UpdateAllCols{}
  709. err = testEngine.Sync(col1)
  710. assert.NoError(t, err)
  711. _, err = testEngine.Insert(col1)
  712. assert.NoError(t, err)
  713. col2 := &UpdateAllCols{col1.Id, true, "", nil}
  714. _, err = testEngine.ID(col2.Id).AllCols().Update(col2)
  715. assert.NoError(t, err)
  716. col3 := &UpdateAllCols{}
  717. has, err = testEngine.ID(col2.Id).Get(col3)
  718. assert.NoError(t, err)
  719. if !has {
  720. err = errors.New(fmt.Sprintf("cannot get id %d", col2.Id))
  721. t.Error(err)
  722. panic(err)
  723. return
  724. }
  725. if *col2 != *col3 {
  726. err = errors.New(fmt.Sprintf("col2 should eq col3"))
  727. t.Error(err)
  728. panic(err)
  729. return
  730. }
  731. {
  732. col1 := &UpdateMustCols{}
  733. err = testEngine.Sync(col1)
  734. assert.NoError(t, err)
  735. _, err = testEngine.Insert(col1)
  736. assert.NoError(t, err)
  737. col2 := &UpdateMustCols{col1.Id, true, ""}
  738. boolStr := testEngine.GetColumnMapper().Obj2Table("Bool")
  739. stringStr := testEngine.GetColumnMapper().Obj2Table("String")
  740. _, err = testEngine.ID(col2.Id).MustCols(boolStr, stringStr).Update(col2)
  741. assert.NoError(t, err)
  742. col3 := &UpdateMustCols{}
  743. has, err := testEngine.ID(col2.Id).Get(col3)
  744. assert.NoError(t, err)
  745. if !has {
  746. err = errors.New(fmt.Sprintf("cannot get id %d", col2.Id))
  747. t.Error(err)
  748. panic(err)
  749. return
  750. }
  751. if *col2 != *col3 {
  752. err = errors.New(fmt.Sprintf("col2 should eq col3"))
  753. t.Error(err)
  754. panic(err)
  755. return
  756. }
  757. }
  758. {
  759. col1 := &UpdateIncr{}
  760. err = testEngine.Sync(col1)
  761. if err != nil {
  762. t.Error(err)
  763. panic(err)
  764. }
  765. _, err = testEngine.Insert(col1)
  766. if err != nil {
  767. t.Error(err)
  768. panic(err)
  769. }
  770. cnt, err := testEngine.ID(col1.Id).Incr("`Cnt`").Update(col1)
  771. if err != nil {
  772. t.Error(err)
  773. panic(err)
  774. }
  775. if cnt != 1 {
  776. err = errors.New("update incr failed")
  777. t.Error(err)
  778. panic(err)
  779. }
  780. newCol := new(UpdateIncr)
  781. has, err := testEngine.ID(col1.Id).Get(newCol)
  782. if err != nil {
  783. t.Error(err)
  784. panic(err)
  785. }
  786. if !has {
  787. err = errors.New("has incr failed")
  788. t.Error(err)
  789. panic(err)
  790. }
  791. if 1 != newCol.Cnt {
  792. err = errors.New("incr failed")
  793. t.Error(err)
  794. panic(err)
  795. }
  796. }
  797. }
  798. func TestUseBool(t *testing.T) {
  799. assert.NoError(t, prepareEngine())
  800. assertSync(t, new(Userinfo))
  801. cnt1, err := testEngine.Count(&Userinfo{})
  802. if err != nil {
  803. t.Error(err)
  804. panic(err)
  805. }
  806. users := make([]Userinfo, 0)
  807. err = testEngine.Find(&users)
  808. if err != nil {
  809. t.Error(err)
  810. panic(err)
  811. }
  812. var fNumber int64
  813. for _, u := range users {
  814. if u.IsMan == false {
  815. fNumber += 1
  816. }
  817. }
  818. cnt2, err := testEngine.UseBool().Update(&Userinfo{IsMan: true})
  819. if err != nil {
  820. t.Error(err)
  821. panic(err)
  822. }
  823. if fNumber != cnt2 {
  824. fmt.Println("cnt1", cnt1, "fNumber", fNumber, "cnt2", cnt2)
  825. /*err = errors.New("Updated number is not corrected.")
  826. t.Error(err)
  827. panic(err)*/
  828. }
  829. _, err = testEngine.Update(&Userinfo{IsMan: true})
  830. if err == nil {
  831. err = errors.New("error condition")
  832. t.Error(err)
  833. panic(err)
  834. }
  835. }
  836. func TestBool(t *testing.T) {
  837. assert.NoError(t, prepareEngine())
  838. assertSync(t, new(Userinfo))
  839. _, err := testEngine.UseBool().Update(&Userinfo{IsMan: true})
  840. if err != nil {
  841. t.Error(err)
  842. panic(err)
  843. }
  844. users := make([]Userinfo, 0)
  845. err = testEngine.Find(&users)
  846. if err != nil {
  847. t.Error(err)
  848. panic(err)
  849. }
  850. for _, user := range users {
  851. if !user.IsMan {
  852. err = errors.New("update bool or find bool error")
  853. t.Error(err)
  854. panic(err)
  855. }
  856. }
  857. _, err = testEngine.UseBool().Update(&Userinfo{IsMan: false})
  858. if err != nil {
  859. t.Error(err)
  860. panic(err)
  861. }
  862. users = make([]Userinfo, 0)
  863. err = testEngine.Find(&users)
  864. if err != nil {
  865. t.Error(err)
  866. panic(err)
  867. }
  868. for _, user := range users {
  869. if user.IsMan {
  870. err = errors.New("update bool or find bool error")
  871. t.Error(err)
  872. panic(err)
  873. }
  874. }
  875. }
  876. func TestNoUpdate(t *testing.T) {
  877. assert.NoError(t, prepareEngine())
  878. type NoUpdate struct {
  879. Id int64
  880. Content string
  881. }
  882. assertSync(t, new(NoUpdate))
  883. cnt, err := testEngine.Insert(&NoUpdate{
  884. Content: "test",
  885. })
  886. assert.NoError(t, err)
  887. assert.EqualValues(t, 1, cnt)
  888. _, err = testEngine.ID(1).Update(&NoUpdate{})
  889. assert.Error(t, err)
  890. assert.EqualValues(t, "No content found to be updated", err.Error())
  891. }
  892. func TestNewUpdate(t *testing.T) {
  893. assert.NoError(t, prepareEngine())
  894. type TbUserInfo struct {
  895. Id int64 `xorm:"pk autoincr unique BIGINT" json:"id"`
  896. Phone string `xorm:"not null unique VARCHAR(20)" json:"phone"`
  897. UserName string `xorm:"VARCHAR(20)" json:"user_name"`
  898. Gender int `xorm:"default 0 INTEGER" json:"gender"`
  899. Pw string `xorm:"VARCHAR(100)" json:"pw"`
  900. Token string `xorm:"TEXT" json:"token"`
  901. Avatar string `xorm:"TEXT" json:"avatar"`
  902. Extras interface{} `xorm:"JSON" json:"extras"`
  903. Created time.Time `xorm:"DATETIME created"`
  904. Updated time.Time `xorm:"DATETIME updated"`
  905. Deleted time.Time `xorm:"DATETIME deleted"`
  906. }
  907. assertSync(t, new(TbUserInfo))
  908. targetUsr := TbUserInfo{Phone: "13126564922"}
  909. changeUsr := TbUserInfo{Token: "ABCDEFG"}
  910. af, err := testEngine.Update(&changeUsr, &targetUsr)
  911. assert.NoError(t, err)
  912. assert.EqualValues(t, 0, af)
  913. af, err = testEngine.Table(new(TbUserInfo)).Where("phone=?", 13126564922).Update(&changeUsr)
  914. assert.NoError(t, err)
  915. assert.EqualValues(t, 0, af)
  916. }
  917. func TestUpdateUpdate(t *testing.T) {
  918. assert.NoError(t, prepareEngine())
  919. type PublicKeyUpdate struct {
  920. Id int64
  921. UpdatedUnix int64 `xorm:"updated"`
  922. }
  923. assertSync(t, new(PublicKeyUpdate))
  924. cnt, err := testEngine.ID(1).Cols("updated_unix").Update(&PublicKeyUpdate{
  925. UpdatedUnix: time.Now().Unix(),
  926. })
  927. assert.NoError(t, err)
  928. assert.EqualValues(t, 0, cnt)
  929. }
  930. func TestCreatedUpdated2(t *testing.T) {
  931. assert.NoError(t, prepareEngine())
  932. type CreatedUpdatedStruct struct {
  933. Id int64
  934. Name string
  935. CreateAt time.Time `xorm:"created" json:"create_at"`
  936. UpdateAt time.Time `xorm:"updated" json:"update_at"`
  937. }
  938. assertSync(t, new(CreatedUpdatedStruct))
  939. var s = CreatedUpdatedStruct{
  940. Name: "test",
  941. }
  942. cnt, err := testEngine.Insert(&s)
  943. assert.NoError(t, err)
  944. assert.EqualValues(t, 1, cnt)
  945. assert.EqualValues(t, s.UpdateAt.Unix(), s.CreateAt.Unix())
  946. time.Sleep(time.Second)
  947. var s1 = CreatedUpdatedStruct{
  948. Name: "test1",
  949. CreateAt: s.CreateAt,
  950. UpdateAt: s.UpdateAt,
  951. }
  952. cnt, err = testEngine.ID(1).Update(&s1)
  953. assert.NoError(t, err)
  954. assert.EqualValues(t, 1, cnt)
  955. assert.EqualValues(t, s.CreateAt.Unix(), s1.CreateAt.Unix())
  956. assert.True(t, s1.UpdateAt.Unix() > s.UpdateAt.Unix())
  957. var s2 CreatedUpdatedStruct
  958. has, err := testEngine.ID(1).Get(&s2)
  959. assert.NoError(t, err)
  960. assert.True(t, has)
  961. assert.EqualValues(t, s.CreateAt.Unix(), s2.CreateAt.Unix())
  962. assert.True(t, s2.UpdateAt.Unix() > s.UpdateAt.Unix())
  963. assert.True(t, s2.UpdateAt.Unix() > s2.CreateAt.Unix())
  964. }
  965. func TestDeletedUpdate(t *testing.T) {
  966. assert.NoError(t, prepareEngine())
  967. type DeletedUpdatedStruct struct {
  968. Id int64
  969. Name string
  970. DeletedAt time.Time `xorm:"deleted"`
  971. }
  972. assertSync(t, new(DeletedUpdatedStruct))
  973. var s = DeletedUpdatedStruct{
  974. Name: "test",
  975. }
  976. cnt, err := testEngine.Insert(&s)
  977. assert.NoError(t, err)
  978. assert.EqualValues(t, 1, cnt)
  979. cnt, err = testEngine.ID(s.Id).Delete(&DeletedUpdatedStruct{})
  980. assert.NoError(t, err)
  981. assert.EqualValues(t, 1, cnt)
  982. s.DeletedAt = time.Time{}
  983. cnt, err = testEngine.Unscoped().Nullable("deleted_at").Update(&s)
  984. assert.NoError(t, err)
  985. assert.EqualValues(t, 1, cnt)
  986. var s1 DeletedUpdatedStruct
  987. has, err := testEngine.ID(s.Id).Get(&s1)
  988. assert.EqualValues(t, true, has)
  989. cnt, err = testEngine.ID(s.Id).Delete(&DeletedUpdatedStruct{})
  990. assert.NoError(t, err)
  991. assert.EqualValues(t, 1, cnt)
  992. cnt, err = testEngine.ID(s.Id).Cols("deleted_at").Update(&DeletedUpdatedStruct{})
  993. assert.EqualValues(t, "No content found to be updated", err.Error())
  994. assert.EqualValues(t, 0, cnt)
  995. cnt, err = testEngine.ID(s.Id).Unscoped().Cols("deleted_at").Update(&DeletedUpdatedStruct{})
  996. assert.NoError(t, err)
  997. assert.EqualValues(t, 1, cnt)
  998. var s2 DeletedUpdatedStruct
  999. has, err = testEngine.ID(s.Id).Get(&s2)
  1000. assert.EqualValues(t, true, has)
  1001. }
  1002. func TestUpdateMapCondition(t *testing.T) {
  1003. assert.NoError(t, prepareEngine())
  1004. type UpdateMapCondition struct {
  1005. Id int64
  1006. String string
  1007. }
  1008. assertSync(t, new(UpdateMapCondition))
  1009. var c = UpdateMapCondition{
  1010. String: "string",
  1011. }
  1012. _, err := testEngine.Insert(&c)
  1013. assert.NoError(t, err)
  1014. cnt, err := testEngine.Update(&UpdateMapCondition{
  1015. String: "string1",
  1016. }, map[string]interface{}{
  1017. "id": c.Id,
  1018. })
  1019. assert.NoError(t, err)
  1020. assert.EqualValues(t, 1, cnt)
  1021. var c2 UpdateMapCondition
  1022. has, err := testEngine.ID(c.Id).Get(&c2)
  1023. assert.NoError(t, err)
  1024. assert.True(t, has)
  1025. assert.EqualValues(t, "string1", c2.String)
  1026. }
  1027. func TestUpdateMapContent(t *testing.T) {
  1028. assert.NoError(t, prepareEngine())
  1029. type UpdateMapContent struct {
  1030. Id int64
  1031. Name string
  1032. IsMan bool
  1033. Age int
  1034. Gender int // 1 is man, 2 is woman
  1035. }
  1036. assertSync(t, new(UpdateMapContent))
  1037. var c = UpdateMapContent{
  1038. Name: "lunny",
  1039. IsMan: true,
  1040. Gender: 1,
  1041. Age: 18,
  1042. }
  1043. _, err := testEngine.Insert(&c)
  1044. assert.NoError(t, err)
  1045. assert.EqualValues(t, 18, c.Age)
  1046. cnt, err := testEngine.Table(new(UpdateMapContent)).ID(c.Id).Update(map[string]interface{}{"age": 0})
  1047. assert.NoError(t, err)
  1048. assert.EqualValues(t, 1, cnt)
  1049. var c1 UpdateMapContent
  1050. has, err := testEngine.ID(c.Id).Get(&c1)
  1051. assert.NoError(t, err)
  1052. assert.True(t, has)
  1053. assert.EqualValues(t, 0, c1.Age)
  1054. cnt, err = testEngine.Table(new(UpdateMapContent)).ID(c.Id).Update(map[string]interface{}{
  1055. "age": 16,
  1056. "is_man": false,
  1057. "gender": 2,
  1058. })
  1059. assert.NoError(t, err)
  1060. assert.EqualValues(t, 1, cnt)
  1061. var c2 UpdateMapContent
  1062. has, err = testEngine.ID(c.Id).Get(&c2)
  1063. assert.NoError(t, err)
  1064. assert.True(t, has)
  1065. assert.EqualValues(t, 16, c2.Age)
  1066. assert.EqualValues(t, false, c2.IsMan)
  1067. assert.EqualValues(t, 2, c2.Gender)
  1068. cnt, err = testEngine.Table(testEngine.TableName(new(UpdateMapContent))).ID(c.Id).Update(map[string]interface{}{
  1069. "age": 15,
  1070. "is_man": true,
  1071. "gender": 1,
  1072. })
  1073. assert.NoError(t, err)
  1074. assert.EqualValues(t, 1, cnt)
  1075. var c3 UpdateMapContent
  1076. has, err = testEngine.ID(c.Id).Get(&c3)
  1077. assert.NoError(t, err)
  1078. assert.True(t, has)
  1079. assert.EqualValues(t, 15, c3.Age)
  1080. assert.EqualValues(t, true, c3.IsMan)
  1081. assert.EqualValues(t, 1, c3.Gender)
  1082. }
  1083. func TestUpdateCondiBean(t *testing.T) {
  1084. type NeedUpdateBean struct {
  1085. Id int64
  1086. Name string
  1087. }
  1088. type NeedUpdateCondiBean struct {
  1089. Name string
  1090. }
  1091. assert.NoError(t, prepareEngine())
  1092. assertSync(t, new(NeedUpdateBean))
  1093. cnt, err := testEngine.Insert(&NeedUpdateBean{
  1094. Name: "name1",
  1095. })
  1096. assert.NoError(t, err)
  1097. assert.EqualValues(t, 1, cnt)
  1098. has, err := testEngine.Exist(&NeedUpdateBean{
  1099. Name: "name1",
  1100. })
  1101. assert.NoError(t, err)
  1102. assert.True(t, has)
  1103. cnt, err = testEngine.Update(&NeedUpdateBean{
  1104. Name: "name2",
  1105. }, &NeedUpdateCondiBean{
  1106. Name: "name1",
  1107. })
  1108. assert.NoError(t, err)
  1109. assert.EqualValues(t, 1, cnt)
  1110. has, err = testEngine.Exist(&NeedUpdateBean{
  1111. Name: "name2",
  1112. })
  1113. assert.NoError(t, err)
  1114. assert.True(t, has)
  1115. cnt, err = testEngine.Update(&NeedUpdateBean{
  1116. Name: "name1",
  1117. }, NeedUpdateCondiBean{
  1118. Name: "name2",
  1119. })
  1120. assert.NoError(t, err)
  1121. assert.EqualValues(t, 1, cnt)
  1122. has, err = testEngine.Exist(&NeedUpdateBean{
  1123. Name: "name1",
  1124. })
  1125. assert.NoError(t, err)
  1126. assert.True(t, has)
  1127. }
  1128. func TestWhereCondErrorWhenUpdate(t *testing.T) {
  1129. type AuthRequestError struct {
  1130. ChallengeToken string
  1131. RequestToken string
  1132. }
  1133. assert.NoError(t, prepareEngine())
  1134. assertSync(t, new(AuthRequestError))
  1135. _, err := testEngine.Cols("challenge_token", "request_token", "challenge_agent", "status").
  1136. Where(&AuthRequestError{ChallengeToken: "1"}).
  1137. Update(&AuthRequestError{
  1138. ChallengeToken: "2",
  1139. })
  1140. assert.Error(t, err)
  1141. assert.EqualValues(t, ErrConditionType, err)
  1142. }
  1143. func TestUpdateDeleted(t *testing.T) {
  1144. assert.NoError(t, prepareEngine())
  1145. type UpdateDeletedStruct struct {
  1146. Id int64
  1147. Name string
  1148. DeletedAt time.Time `xorm:"deleted"`
  1149. }
  1150. assertSync(t, new(UpdateDeletedStruct))
  1151. var s = UpdateDeletedStruct{
  1152. Name: "test",
  1153. }
  1154. cnt, err := testEngine.Insert(&s)
  1155. assert.NoError(t, err)
  1156. assert.EqualValues(t, 1, cnt)
  1157. cnt, err = testEngine.ID(s.Id).Delete(&UpdateDeletedStruct{})
  1158. assert.NoError(t, err)
  1159. assert.EqualValues(t, 1, cnt)
  1160. cnt, err = testEngine.ID(s.Id).Update(&UpdateDeletedStruct{
  1161. Name: "test1",
  1162. })
  1163. assert.NoError(t, err)
  1164. assert.EqualValues(t, 0, cnt)
  1165. cnt, err = testEngine.Table(&UpdateDeletedStruct{}).ID(s.Id).Update(map[string]interface{}{
  1166. "name": "test1",
  1167. })
  1168. assert.NoError(t, err)
  1169. assert.EqualValues(t, 0, cnt)
  1170. cnt, err = testEngine.ID(s.Id).Unscoped().Update(&UpdateDeletedStruct{
  1171. Name: "test1",
  1172. })
  1173. assert.NoError(t, err)
  1174. assert.EqualValues(t, 1, cnt)
  1175. }
  1176. func TestUpdateExprs(t *testing.T) {
  1177. assert.NoError(t, prepareEngine())
  1178. type UpdateExprs struct {
  1179. Id int64
  1180. NumIssues int
  1181. Name string
  1182. }
  1183. assertSync(t, new(UpdateExprs))
  1184. _, err := testEngine.Insert(&UpdateExprs{
  1185. NumIssues: 1,
  1186. Name: "lunny",
  1187. })
  1188. assert.NoError(t, err)
  1189. _, err = testEngine.SetExpr("num_issues", "num_issues+1").AllCols().Update(&UpdateExprs{
  1190. NumIssues: 3,
  1191. Name: "lunny xiao",
  1192. })
  1193. assert.NoError(t, err)
  1194. var ue UpdateExprs
  1195. has, err := testEngine.Get(&ue)
  1196. assert.NoError(t, err)
  1197. assert.True(t, has)
  1198. assert.EqualValues(t, 2, ue.NumIssues)
  1199. assert.EqualValues(t, "lunny xiao", ue.Name)
  1200. }