session_insert_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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. "reflect"
  9. "testing"
  10. "time"
  11. "github.com/stretchr/testify/assert"
  12. )
  13. func TestInsertOne(t *testing.T) {
  14. assert.NoError(t, prepareEngine())
  15. type Test struct {
  16. Id int64 `xorm:"autoincr pk"`
  17. Msg string `xorm:"varchar(255)"`
  18. Created time.Time `xorm:"created"`
  19. }
  20. assert.NoError(t, testEngine.Sync2(new(Test)))
  21. data := Test{Msg: "hi"}
  22. _, err := testEngine.InsertOne(data)
  23. assert.NoError(t, err)
  24. }
  25. func TestInsertOne2(t *testing.T) {
  26. assert.NoError(t, prepareEngine())
  27. type Test2 struct {
  28. Id int64 `xorm:"autoincr pk"`
  29. Msg string `xorm:"varchar(255)"`
  30. Created time.Time `xorm:"datetime created"`
  31. }
  32. assert.NoError(t, testEngine.Sync2(new(Test2)))
  33. data := Test2{Msg: "hi"}
  34. _, err := testEngine.InsertOne(data)
  35. assert.NoError(t, err)
  36. }
  37. func TestInsertMulti(t *testing.T) {
  38. assert.NoError(t, prepareEngine())
  39. type TestMulti struct {
  40. Id int64 `xorm:"int(11) pk"`
  41. Name string `xorm:"varchar(255)"`
  42. }
  43. assert.NoError(t, testEngine.Sync2(new(TestMulti)))
  44. num, err := insertMultiDatas(1,
  45. append([]TestMulti{}, TestMulti{1, "test1"}, TestMulti{2, "test2"}, TestMulti{3, "test3"}))
  46. assert.NoError(t, err)
  47. assert.EqualValues(t, 3, num)
  48. }
  49. func insertMultiDatas(step int, datas interface{}) (num int64, err error) {
  50. sliceValue := reflect.Indirect(reflect.ValueOf(datas))
  51. var iLen int64
  52. if sliceValue.Kind() != reflect.Slice {
  53. return 0, fmt.Errorf("not silce")
  54. }
  55. iLen = int64(sliceValue.Len())
  56. if iLen == 0 {
  57. return
  58. }
  59. session := testEngine.NewSession()
  60. defer session.Close()
  61. if err = callbackLooper(datas, step,
  62. func(innerDatas interface{}) error {
  63. n, e := session.InsertMulti(innerDatas)
  64. if e != nil {
  65. return e
  66. }
  67. num += n
  68. return nil
  69. }); err != nil {
  70. return 0, err
  71. } else if num != iLen {
  72. return 0, fmt.Errorf("num error: %d - %d", num, iLen)
  73. }
  74. return
  75. }
  76. func callbackLooper(datas interface{}, step int, actionFunc func(interface{}) error) (err error) {
  77. sliceValue := reflect.Indirect(reflect.ValueOf(datas))
  78. if sliceValue.Kind() != reflect.Slice {
  79. return fmt.Errorf("not slice")
  80. }
  81. if sliceValue.Len() <= 0 {
  82. return
  83. }
  84. tempLen := 0
  85. processedLen := sliceValue.Len()
  86. for i := 0; i < sliceValue.Len(); i += step {
  87. if processedLen > step {
  88. tempLen = i + step
  89. } else {
  90. tempLen = sliceValue.Len()
  91. }
  92. var tempInterface []interface{}
  93. for j := i; j < tempLen; j++ {
  94. tempInterface = append(tempInterface, sliceValue.Index(j).Interface())
  95. }
  96. if err = actionFunc(tempInterface); err != nil {
  97. return
  98. }
  99. processedLen = processedLen - step
  100. }
  101. return
  102. }
  103. func TestInsertOneIfPkIsPoint(t *testing.T) {
  104. assert.NoError(t, prepareEngine())
  105. type TestPoint struct {
  106. Id *int64 `xorm:"autoincr pk notnull 'id'"`
  107. Msg *string `xorm:"varchar(255)"`
  108. Created *time.Time `xorm:"created"`
  109. }
  110. assert.NoError(t, testEngine.Sync2(new(TestPoint)))
  111. msg := "hi"
  112. data := TestPoint{Msg: &msg}
  113. _, err := testEngine.InsertOne(&data)
  114. assert.NoError(t, err)
  115. }
  116. func TestInsertOneIfPkIsPointRename(t *testing.T) {
  117. assert.NoError(t, prepareEngine())
  118. type ID *int64
  119. type TestPoint2 struct {
  120. Id ID `xorm:"autoincr pk notnull 'id'"`
  121. Msg *string `xorm:"varchar(255)"`
  122. Created *time.Time `xorm:"created"`
  123. }
  124. assert.NoError(t, testEngine.Sync2(new(TestPoint2)))
  125. msg := "hi"
  126. data := TestPoint2{Msg: &msg}
  127. _, err := testEngine.InsertOne(&data)
  128. assert.NoError(t, err)
  129. }
  130. func TestInsert(t *testing.T) {
  131. assert.NoError(t, prepareEngine())
  132. assertSync(t, new(Userinfo))
  133. user := Userinfo{0, "xiaolunwen", "dev", "lunny", time.Now(),
  134. Userdetail{Id: 1}, 1.78, []byte{1, 2, 3}, true}
  135. cnt, err := testEngine.Insert(&user)
  136. assert.NoError(t, err)
  137. assert.EqualValues(t, 1, cnt, "insert not returned 1")
  138. assert.True(t, user.Uid > 0, "not return id error")
  139. user.Uid = 0
  140. cnt, err = testEngine.Insert(&user)
  141. // Username is unique, so this should return error
  142. assert.Error(t, err, "insert should fail but no error returned")
  143. assert.EqualValues(t, 0, cnt, "insert not returned 1")
  144. if err == nil {
  145. panic("should return err")
  146. }
  147. }
  148. func TestInsertAutoIncr(t *testing.T) {
  149. assert.NoError(t, prepareEngine())
  150. assertSync(t, new(Userinfo))
  151. // auto increment insert
  152. user := Userinfo{Username: "xiaolunwen2", Departname: "dev", Alias: "lunny", Created: time.Now(),
  153. Detail: Userdetail{Id: 1}, Height: 1.78, Avatar: []byte{1, 2, 3}, IsMan: true}
  154. cnt, err := testEngine.Insert(&user)
  155. fmt.Println(user.Uid)
  156. if err != nil {
  157. t.Error(err)
  158. panic(err)
  159. }
  160. if cnt != 1 {
  161. err = errors.New("insert not returned 1")
  162. t.Error(err)
  163. panic(err)
  164. }
  165. if user.Uid <= 0 {
  166. t.Error(errors.New("not return id error"))
  167. }
  168. }
  169. type DefaultInsert struct {
  170. Id int64
  171. Status int `xorm:"default -1"`
  172. Name string
  173. Created time.Time `xorm:"created"`
  174. Updated time.Time `xorm:"updated"`
  175. }
  176. func TestInsertDefault(t *testing.T) {
  177. assert.NoError(t, prepareEngine())
  178. di := new(DefaultInsert)
  179. err := testEngine.Sync2(di)
  180. assert.NoError(t, err)
  181. var di2 = DefaultInsert{Name: "test"}
  182. _, err = testEngine.Omit(testEngine.GetColumnMapper().Obj2Table("Status")).Insert(&di2)
  183. assert.NoError(t, err)
  184. has, err := testEngine.Desc("(id)").Get(di)
  185. assert.NoError(t, err)
  186. if !has {
  187. err = errors.New("error with no data")
  188. t.Error(err)
  189. panic(err)
  190. }
  191. if di.Status != -1 {
  192. err = errors.New("inserted error data")
  193. t.Error(err)
  194. panic(err)
  195. }
  196. if di2.Updated.Unix() != di.Updated.Unix() {
  197. err = errors.New("updated should equal")
  198. t.Error(err, di.Updated, di2.Updated)
  199. panic(err)
  200. }
  201. if di2.Created.Unix() != di.Created.Unix() {
  202. err = errors.New("created should equal")
  203. t.Error(err, di.Created, di2.Created)
  204. panic(err)
  205. }
  206. }
  207. type DefaultInsert2 struct {
  208. Id int64
  209. Name string
  210. Url string `xorm:"text"`
  211. CheckTime time.Time `xorm:"not null default '2000-01-01 00:00:00' TIMESTAMP"`
  212. }
  213. func TestInsertDefault2(t *testing.T) {
  214. assert.NoError(t, prepareEngine())
  215. di := new(DefaultInsert2)
  216. err := testEngine.Sync2(di)
  217. if err != nil {
  218. t.Error(err)
  219. }
  220. var di2 = DefaultInsert2{Name: "test"}
  221. _, err = testEngine.Omit(testEngine.GetColumnMapper().Obj2Table("CheckTime")).Insert(&di2)
  222. if err != nil {
  223. t.Error(err)
  224. }
  225. has, err := testEngine.Desc("(id)").Get(di)
  226. if err != nil {
  227. t.Error(err)
  228. }
  229. if !has {
  230. err = errors.New("error with no data")
  231. t.Error(err)
  232. panic(err)
  233. }
  234. has, err = testEngine.NoAutoCondition().Desc("(id)").Get(&di2)
  235. if err != nil {
  236. t.Error(err)
  237. }
  238. if !has {
  239. err = errors.New("error with no data")
  240. t.Error(err)
  241. panic(err)
  242. }
  243. if *di != di2 {
  244. err = fmt.Errorf("%v is not equal to %v", di, di2)
  245. t.Error(err)
  246. panic(err)
  247. }
  248. /*if di2.Updated.Unix() != di.Updated.Unix() {
  249. err = errors.New("updated should equal")
  250. t.Error(err, di.Updated, di2.Updated)
  251. panic(err)
  252. }
  253. if di2.Created.Unix() != di.Created.Unix() {
  254. err = errors.New("created should equal")
  255. t.Error(err, di.Created, di2.Created)
  256. panic(err)
  257. }*/
  258. }
  259. type CreatedInsert struct {
  260. Id int64
  261. Created time.Time `xorm:"created"`
  262. }
  263. type CreatedInsert2 struct {
  264. Id int64
  265. Created int64 `xorm:"created"`
  266. }
  267. type CreatedInsert3 struct {
  268. Id int64
  269. Created int `xorm:"created bigint"`
  270. }
  271. type CreatedInsert4 struct {
  272. Id int64
  273. Created int `xorm:"created"`
  274. }
  275. type CreatedInsert5 struct {
  276. Id int64
  277. Created time.Time `xorm:"created bigint"`
  278. }
  279. type CreatedInsert6 struct {
  280. Id int64
  281. Created time.Time `xorm:"created bigint"`
  282. }
  283. func TestInsertCreated(t *testing.T) {
  284. assert.NoError(t, prepareEngine())
  285. di := new(CreatedInsert)
  286. err := testEngine.Sync2(di)
  287. if err != nil {
  288. t.Fatal(err)
  289. }
  290. ci := &CreatedInsert{}
  291. _, err = testEngine.Insert(ci)
  292. if err != nil {
  293. t.Fatal(err)
  294. }
  295. has, err := testEngine.Desc("(id)").Get(di)
  296. if err != nil {
  297. t.Fatal(err)
  298. }
  299. if !has {
  300. t.Fatal(ErrNotExist)
  301. }
  302. if ci.Created.Unix() != di.Created.Unix() {
  303. t.Fatal("should equal:", ci, di)
  304. }
  305. fmt.Println("ci:", ci, "di:", di)
  306. di2 := new(CreatedInsert2)
  307. err = testEngine.Sync2(di2)
  308. if err != nil {
  309. t.Fatal(err)
  310. }
  311. ci2 := &CreatedInsert2{}
  312. _, err = testEngine.Insert(ci2)
  313. if err != nil {
  314. t.Fatal(err)
  315. }
  316. has, err = testEngine.Desc("(id)").Get(di2)
  317. if err != nil {
  318. t.Fatal(err)
  319. }
  320. if !has {
  321. t.Fatal(ErrNotExist)
  322. }
  323. if ci2.Created != di2.Created {
  324. t.Fatal("should equal:", ci2, di2)
  325. }
  326. fmt.Println("ci2:", ci2, "di2:", di2)
  327. di3 := new(CreatedInsert3)
  328. err = testEngine.Sync2(di3)
  329. if err != nil {
  330. t.Fatal(err)
  331. }
  332. ci3 := &CreatedInsert3{}
  333. _, err = testEngine.Insert(ci3)
  334. if err != nil {
  335. t.Fatal(err)
  336. }
  337. has, err = testEngine.Desc("(id)").Get(di3)
  338. if err != nil {
  339. t.Fatal(err)
  340. }
  341. if !has {
  342. t.Fatal(ErrNotExist)
  343. }
  344. if ci3.Created != di3.Created {
  345. t.Fatal("should equal:", ci3, di3)
  346. }
  347. fmt.Println("ci3:", ci3, "di3:", di3)
  348. di4 := new(CreatedInsert4)
  349. err = testEngine.Sync2(di4)
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. ci4 := &CreatedInsert4{}
  354. _, err = testEngine.Insert(ci4)
  355. if err != nil {
  356. t.Fatal(err)
  357. }
  358. has, err = testEngine.Desc("(id)").Get(di4)
  359. if err != nil {
  360. t.Fatal(err)
  361. }
  362. if !has {
  363. t.Fatal(ErrNotExist)
  364. }
  365. if ci4.Created != di4.Created {
  366. t.Fatal("should equal:", ci4, di4)
  367. }
  368. fmt.Println("ci4:", ci4, "di4:", di4)
  369. di5 := new(CreatedInsert5)
  370. err = testEngine.Sync2(di5)
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. ci5 := &CreatedInsert5{}
  375. _, err = testEngine.Insert(ci5)
  376. if err != nil {
  377. t.Fatal(err)
  378. }
  379. has, err = testEngine.Desc("(id)").Get(di5)
  380. if err != nil {
  381. t.Fatal(err)
  382. }
  383. if !has {
  384. t.Fatal(ErrNotExist)
  385. }
  386. if ci5.Created.Unix() != di5.Created.Unix() {
  387. t.Fatal("should equal:", ci5, di5)
  388. }
  389. fmt.Println("ci5:", ci5, "di5:", di5)
  390. di6 := new(CreatedInsert6)
  391. err = testEngine.Sync2(di6)
  392. if err != nil {
  393. t.Fatal(err)
  394. }
  395. oldTime := time.Now().Add(-time.Hour)
  396. ci6 := &CreatedInsert6{Created: oldTime}
  397. _, err = testEngine.Insert(ci6)
  398. if err != nil {
  399. t.Fatal(err)
  400. }
  401. has, err = testEngine.Desc("(id)").Get(di6)
  402. if err != nil {
  403. t.Fatal(err)
  404. }
  405. if !has {
  406. t.Fatal(ErrNotExist)
  407. }
  408. if ci6.Created.Unix() != di6.Created.Unix() {
  409. t.Fatal("should equal:", ci6, di6)
  410. }
  411. fmt.Println("ci6:", ci6, "di6:", di6)
  412. }
  413. type JsonTime time.Time
  414. func (j JsonTime) format() string {
  415. t := time.Time(j)
  416. if t.IsZero() {
  417. return ""
  418. }
  419. return t.Format("2006-01-02")
  420. }
  421. func (j JsonTime) MarshalText() ([]byte, error) {
  422. return []byte(j.format()), nil
  423. }
  424. func (j JsonTime) MarshalJSON() ([]byte, error) {
  425. return []byte(`"` + j.format() + `"`), nil
  426. }
  427. func TestDefaultTime3(t *testing.T) {
  428. type PrepareTask struct {
  429. Id int `xorm:"not null pk autoincr INT(11)" json:"id"`
  430. // ...
  431. StartTime JsonTime `xorm:"not null default '2006-01-02 15:04:05' TIMESTAMP index" json:"start_time"`
  432. EndTime JsonTime `xorm:"not null default '2006-01-02 15:04:05' TIMESTAMP" json:"end_time"`
  433. Cuser string `xorm:"not null default '' VARCHAR(64) index" json:"cuser"`
  434. Muser string `xorm:"not null default '' VARCHAR(64)" json:"muser"`
  435. Ctime JsonTime `xorm:"not null default CURRENT_TIMESTAMP TIMESTAMP created" json:"ctime"`
  436. Mtime JsonTime `xorm:"not null default CURRENT_TIMESTAMP TIMESTAMP updated" json:"mtime"`
  437. }
  438. assert.NoError(t, prepareEngine())
  439. assertSync(t, new(PrepareTask))
  440. prepareTask := &PrepareTask{
  441. StartTime: JsonTime(time.Now()),
  442. Cuser: "userId",
  443. Muser: "userId",
  444. }
  445. cnt, err := testEngine.Omit("end_time").InsertOne(prepareTask)
  446. assert.NoError(t, err)
  447. assert.EqualValues(t, 1, cnt)
  448. }
  449. type MyJsonTime struct {
  450. Id int64 `json:"id"`
  451. Created JsonTime `xorm:"created" json:"created_at"`
  452. }
  453. func TestCreatedJsonTime(t *testing.T) {
  454. assert.NoError(t, prepareEngine())
  455. di5 := new(MyJsonTime)
  456. err := testEngine.Sync2(di5)
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. ci5 := &MyJsonTime{}
  461. _, err = testEngine.Insert(ci5)
  462. if err != nil {
  463. t.Fatal(err)
  464. }
  465. has, err := testEngine.Desc("(id)").Get(di5)
  466. if err != nil {
  467. t.Fatal(err)
  468. }
  469. if !has {
  470. t.Fatal(ErrNotExist)
  471. }
  472. if time.Time(ci5.Created).Unix() != time.Time(di5.Created).Unix() {
  473. t.Fatal("should equal:", time.Time(ci5.Created).Unix(), time.Time(di5.Created).Unix())
  474. }
  475. fmt.Println("ci5:", ci5, "di5:", di5)
  476. var dis = make([]MyJsonTime, 0)
  477. err = testEngine.Find(&dis)
  478. if err != nil {
  479. t.Fatal(err)
  480. }
  481. }
  482. func TestInsertMulti2(t *testing.T) {
  483. assert.NoError(t, prepareEngine())
  484. assertSync(t, new(Userinfo))
  485. users := []Userinfo{
  486. {Username: "xlw", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  487. {Username: "xlw2", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  488. {Username: "xlw11", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  489. {Username: "xlw22", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  490. }
  491. cnt, err := testEngine.Insert(&users)
  492. if err != nil {
  493. t.Error(err)
  494. panic(err)
  495. }
  496. if cnt != int64(len(users)) {
  497. err = errors.New("insert not returned 1")
  498. t.Error(err)
  499. panic(err)
  500. return
  501. }
  502. users2 := []*Userinfo{
  503. &Userinfo{Username: "1xlw", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  504. &Userinfo{Username: "1xlw2", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  505. &Userinfo{Username: "1xlw11", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  506. &Userinfo{Username: "1xlw22", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  507. }
  508. cnt, err = testEngine.Insert(&users2)
  509. if err != nil {
  510. t.Error(err)
  511. panic(err)
  512. }
  513. if cnt != int64(len(users2)) {
  514. err = errors.New(fmt.Sprintf("insert not returned %v", len(users2)))
  515. t.Error(err)
  516. panic(err)
  517. }
  518. }
  519. func TestInsertTwoTable(t *testing.T) {
  520. assert.NoError(t, prepareEngine())
  521. assertSync(t, new(Userinfo), new(Userdetail))
  522. userdetail := Userdetail{ /*Id: 1, */ Intro: "I'm a very beautiful women.", Profile: "sfsaf"}
  523. userinfo := Userinfo{Username: "xlw3", Departname: "dev", Alias: "lunny4", Created: time.Now(), Detail: userdetail}
  524. cnt, err := testEngine.Insert(&userinfo, &userdetail)
  525. if err != nil {
  526. t.Error(err)
  527. panic(err)
  528. }
  529. if userinfo.Uid <= 0 {
  530. err = errors.New("not return id error")
  531. t.Error(err)
  532. panic(err)
  533. }
  534. if userdetail.Id <= 0 {
  535. err = errors.New("not return id error")
  536. t.Error(err)
  537. panic(err)
  538. }
  539. if cnt != 2 {
  540. err = errors.New("insert not returned 2")
  541. t.Error(err)
  542. panic(err)
  543. }
  544. }
  545. func TestInsertCreatedInt64(t *testing.T) {
  546. assert.NoError(t, prepareEngine())
  547. type TestCreatedInt64 struct {
  548. Id int64 `xorm:"autoincr pk"`
  549. Msg string `xorm:"varchar(255)"`
  550. Created int64 `xorm:"created"`
  551. }
  552. assert.NoError(t, testEngine.Sync2(new(TestCreatedInt64)))
  553. data := TestCreatedInt64{Msg: "hi"}
  554. now := time.Now()
  555. cnt, err := testEngine.Insert(&data)
  556. assert.NoError(t, err)
  557. assert.EqualValues(t, 1, cnt)
  558. assert.True(t, now.Unix() <= data.Created)
  559. var data2 TestCreatedInt64
  560. has, err := testEngine.Get(&data2)
  561. assert.NoError(t, err)
  562. assert.True(t, has)
  563. assert.EqualValues(t, data.Created, data2.Created)
  564. }
  565. type MyUserinfo Userinfo
  566. func (MyUserinfo) TableName() string {
  567. return "user_info"
  568. }
  569. func TestInsertMulti3(t *testing.T) {
  570. assert.NoError(t, prepareEngine())
  571. testEngine.ShowSQL(true)
  572. assertSync(t, new(MyUserinfo))
  573. users := []MyUserinfo{
  574. {Username: "xlw", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  575. {Username: "xlw2", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  576. {Username: "xlw11", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  577. {Username: "xlw22", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  578. }
  579. cnt, err := testEngine.Insert(&users)
  580. assert.NoError(t, err)
  581. assert.EqualValues(t, len(users), cnt)
  582. users2 := []*MyUserinfo{
  583. &MyUserinfo{Username: "1xlw", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  584. &MyUserinfo{Username: "1xlw2", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  585. &MyUserinfo{Username: "1xlw11", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  586. &MyUserinfo{Username: "1xlw22", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  587. }
  588. cnt, err = testEngine.Insert(&users2)
  589. assert.NoError(t, err)
  590. assert.EqualValues(t, len(users), cnt)
  591. }
  592. type MyUserinfo2 struct {
  593. Uid int64 `xorm:"id pk not null autoincr"`
  594. Username string `xorm:"unique"`
  595. Departname string
  596. Alias string `xorm:"-"`
  597. Created time.Time
  598. Detail Userdetail `xorm:"detail_id int(11)"`
  599. Height float64
  600. Avatar []byte
  601. IsMan bool
  602. }
  603. func (MyUserinfo2) TableName() string {
  604. return "user_info"
  605. }
  606. func TestInsertMulti4(t *testing.T) {
  607. assert.NoError(t, prepareEngine())
  608. testEngine.ShowSQL(false)
  609. assertSync(t, new(MyUserinfo2))
  610. testEngine.ShowSQL(true)
  611. users := []MyUserinfo2{
  612. {Username: "xlw", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  613. {Username: "xlw2", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  614. {Username: "xlw11", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  615. {Username: "xlw22", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  616. }
  617. cnt, err := testEngine.Insert(&users)
  618. assert.NoError(t, err)
  619. assert.EqualValues(t, len(users), cnt)
  620. users2 := []*MyUserinfo2{
  621. &MyUserinfo2{Username: "1xlw", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  622. &MyUserinfo2{Username: "1xlw2", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  623. &MyUserinfo2{Username: "1xlw11", Departname: "dev", Alias: "lunny2", Created: time.Now()},
  624. &MyUserinfo2{Username: "1xlw22", Departname: "dev", Alias: "lunny3", Created: time.Now()},
  625. }
  626. cnt, err = testEngine.Insert(&users2)
  627. assert.NoError(t, err)
  628. assert.EqualValues(t, len(users), cnt)
  629. }
  630. func TestAnonymousStruct(t *testing.T) {
  631. type PlainObject struct {
  632. ID uint64 `json:"id,string" xorm:"'ID' pk autoincr"`
  633. Desc string `json:"desc" xorm:"'DESC' notnull"`
  634. }
  635. type PlainFoo struct {
  636. PlainObject `xorm:"extends"` // primary key defined in extends struct
  637. Width uint32 `json:"width" xorm:"'WIDTH' notnull"`
  638. Height uint32 `json:"height" xorm:"'HEIGHT' notnull"`
  639. Ext struct {
  640. F1 uint32 `json:"f1,omitempty"`
  641. F2 uint32 `json:"f2,omitempty"`
  642. } `json:"ext" xorm:"'EXT' json notnull"`
  643. }
  644. assert.NoError(t, prepareEngine())
  645. assertSync(t, new(PlainFoo))
  646. _, err := testEngine.Insert(&PlainFoo{
  647. PlainObject: PlainObject{
  648. Desc: "test",
  649. },
  650. Width: 10,
  651. Height: 20,
  652. Ext: struct {
  653. F1 uint32 `json:"f1,omitempty"`
  654. F2 uint32 `json:"f2,omitempty"`
  655. }{
  656. F1: 11,
  657. F2: 12,
  658. },
  659. })
  660. assert.NoError(t, err)
  661. }
  662. func TestInsertMap(t *testing.T) {
  663. type InsertMap struct {
  664. Id int64
  665. Width uint32
  666. Height uint32
  667. Name string
  668. }
  669. assert.NoError(t, prepareEngine())
  670. assertSync(t, new(InsertMap))
  671. cnt, err := testEngine.Table(new(InsertMap)).Insert(map[string]interface{}{
  672. "width": 20,
  673. "height": 10,
  674. "name": "lunny",
  675. })
  676. assert.NoError(t, err)
  677. assert.EqualValues(t, 1, cnt)
  678. var im InsertMap
  679. has, err := testEngine.Get(&im)
  680. assert.NoError(t, err)
  681. assert.True(t, has)
  682. assert.EqualValues(t, 20, im.Width)
  683. assert.EqualValues(t, 10, im.Height)
  684. assert.EqualValues(t, "lunny", im.Name)
  685. cnt, err = testEngine.Table("insert_map").Insert(map[string]interface{}{
  686. "width": 30,
  687. "height": 10,
  688. "name": "lunny",
  689. })
  690. assert.NoError(t, err)
  691. assert.EqualValues(t, 1, cnt)
  692. var ims []InsertMap
  693. err = testEngine.Find(&ims)
  694. assert.NoError(t, err)
  695. assert.EqualValues(t, 2, len(ims))
  696. assert.EqualValues(t, 20, ims[0].Width)
  697. assert.EqualValues(t, 10, ims[0].Height)
  698. assert.EqualValues(t, "lunny", ims[0].Name)
  699. assert.EqualValues(t, 30, ims[1].Width)
  700. assert.EqualValues(t, 10, ims[1].Height)
  701. assert.EqualValues(t, "lunny", ims[1].Name)
  702. cnt, err = testEngine.Table("insert_map").Insert([]map[string]interface{}{
  703. {
  704. "width": 40,
  705. "height": 10,
  706. "name": "lunny",
  707. },
  708. {
  709. "width": 50,
  710. "height": 10,
  711. "name": "lunny",
  712. },
  713. })
  714. assert.NoError(t, err)
  715. assert.EqualValues(t, 2, cnt)
  716. ims = make([]InsertMap, 0, 4)
  717. err = testEngine.Find(&ims)
  718. assert.NoError(t, err)
  719. assert.EqualValues(t, 4, len(ims))
  720. assert.EqualValues(t, 20, ims[0].Width)
  721. assert.EqualValues(t, 10, ims[0].Height)
  722. assert.EqualValues(t, "lunny", ims[1].Name)
  723. assert.EqualValues(t, 30, ims[1].Width)
  724. assert.EqualValues(t, 10, ims[1].Height)
  725. assert.EqualValues(t, "lunny", ims[1].Name)
  726. assert.EqualValues(t, 40, ims[2].Width)
  727. assert.EqualValues(t, 10, ims[2].Height)
  728. assert.EqualValues(t, "lunny", ims[2].Name)
  729. assert.EqualValues(t, 50, ims[3].Width)
  730. assert.EqualValues(t, 10, ims[3].Height)
  731. assert.EqualValues(t, "lunny", ims[3].Name)
  732. }
  733. /*INSERT INTO `issue` (`repo_id`, `poster_id`, ... ,`name`, `content`, ... ,`index`)
  734. SELECT $1, $2, ..., $14, $15, ..., MAX(`index`) + 1 FROM `issue` WHERE `repo_id` = $1;
  735. */
  736. func TestInsertWhere(t *testing.T) {
  737. type InsertWhere struct {
  738. Id int64
  739. Index int `xorm:"unique(s) notnull"`
  740. RepoId int64 `xorm:"unique(s)"`
  741. Width uint32
  742. Height uint32
  743. Name string
  744. }
  745. assert.NoError(t, prepareEngine())
  746. assertSync(t, new(InsertWhere))
  747. var i = InsertWhere{
  748. RepoId: 1,
  749. Width: 10,
  750. Height: 20,
  751. Name: "trest",
  752. }
  753. inserted, err := testEngine.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  754. Where("repo_id=?", 1).
  755. Insert(&i)
  756. assert.NoError(t, err)
  757. assert.EqualValues(t, 1, inserted)
  758. assert.EqualValues(t, 1, i.Id)
  759. var j InsertWhere
  760. has, err := testEngine.ID(i.Id).Get(&j)
  761. assert.NoError(t, err)
  762. assert.True(t, has)
  763. i.Index = 1
  764. assert.EqualValues(t, i, j)
  765. inserted, err = testEngine.Table(new(InsertWhere)).Where("repo_id=?", 1).
  766. SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  767. Insert(map[string]interface{}{
  768. "repo_id": 1,
  769. "width": 20,
  770. "height": 40,
  771. "name": "trest2",
  772. })
  773. assert.NoError(t, err)
  774. assert.EqualValues(t, 1, inserted)
  775. var j2 InsertWhere
  776. has, err = testEngine.ID(2).Get(&j2)
  777. assert.NoError(t, err)
  778. assert.True(t, has)
  779. assert.EqualValues(t, 1, j2.RepoId)
  780. assert.EqualValues(t, 20, j2.Width)
  781. assert.EqualValues(t, 40, j2.Height)
  782. assert.EqualValues(t, "trest2", j2.Name)
  783. assert.EqualValues(t, 2, j2.Index)
  784. }