create_test.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package gorm_test
  2. import (
  3. "os"
  4. "reflect"
  5. "testing"
  6. "time"
  7. "github.com/jinzhu/now"
  8. )
  9. func TestCreate(t *testing.T) {
  10. float := 35.03554004971999
  11. now := time.Now()
  12. user := User{Name: "CreateUser", Age: 18, Birthday: &now, UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float}
  13. if !DB.NewRecord(user) || !DB.NewRecord(&user) {
  14. t.Error("User should be new record before create")
  15. }
  16. if count := DB.Save(&user).RowsAffected; count != 1 {
  17. t.Error("There should be one record be affected when create record")
  18. }
  19. if DB.NewRecord(user) || DB.NewRecord(&user) {
  20. t.Error("User should not new record after save")
  21. }
  22. var newUser User
  23. if err := DB.First(&newUser, user.Id).Error; err != nil {
  24. t.Errorf("No error should happen, but got %v", err)
  25. }
  26. if !reflect.DeepEqual(newUser.PasswordHash, []byte{'f', 'a', 'k', '4'}) {
  27. t.Errorf("User's PasswordHash should be saved ([]byte)")
  28. }
  29. if newUser.Age != 18 {
  30. t.Errorf("User's Age should be saved (int)")
  31. }
  32. if newUser.UserNum != Num(111) {
  33. t.Errorf("User's UserNum should be saved (custom type), but got %v", newUser.UserNum)
  34. }
  35. if newUser.Latitude != float {
  36. t.Errorf("Float64 should not be changed after save")
  37. }
  38. if user.CreatedAt.IsZero() {
  39. t.Errorf("Should have created_at after create")
  40. }
  41. if newUser.CreatedAt.IsZero() {
  42. t.Errorf("Should have created_at after create")
  43. }
  44. DB.Model(user).Update("name", "create_user_new_name")
  45. DB.First(&user, user.Id)
  46. if user.CreatedAt.Format(time.RFC3339Nano) != newUser.CreatedAt.Format(time.RFC3339Nano) {
  47. t.Errorf("CreatedAt should not be changed after update")
  48. }
  49. }
  50. func TestCreateEmptyStrut(t *testing.T) {
  51. type EmptyStruct struct {
  52. ID uint
  53. }
  54. DB.AutoMigrate(&EmptyStruct{})
  55. if err := DB.Create(&EmptyStruct{}).Error; err != nil {
  56. t.Errorf("No error should happen when creating user, but got %v", err)
  57. }
  58. }
  59. func TestCreateWithExistingTimestamp(t *testing.T) {
  60. user := User{Name: "CreateUserExistingTimestamp"}
  61. timeA := now.MustParse("2016-01-01")
  62. user.CreatedAt = timeA
  63. user.UpdatedAt = timeA
  64. DB.Save(&user)
  65. if user.CreatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
  66. t.Errorf("CreatedAt should not be changed")
  67. }
  68. if user.UpdatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
  69. t.Errorf("UpdatedAt should not be changed")
  70. }
  71. var newUser User
  72. DB.First(&newUser, user.Id)
  73. if newUser.CreatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
  74. t.Errorf("CreatedAt should not be changed")
  75. }
  76. if newUser.UpdatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
  77. t.Errorf("UpdatedAt should not be changed")
  78. }
  79. }
  80. func TestCreateWithNowFuncOverride(t *testing.T) {
  81. user1 := User{Name: "CreateUserTimestampOverride"}
  82. timeA := now.MustParse("2016-01-01")
  83. // do DB.New() because we don't want this test to affect other tests
  84. db1 := DB.New()
  85. // set the override to use static timeA
  86. db1.SetNowFuncOverride(func() time.Time {
  87. return timeA
  88. })
  89. // call .New again to check the override is carried over as well during clone
  90. db1 = db1.New()
  91. db1.Save(&user1)
  92. if user1.CreatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
  93. t.Errorf("CreatedAt be using the nowFuncOverride")
  94. }
  95. if user1.UpdatedAt.UTC().Format(time.RFC3339) != timeA.UTC().Format(time.RFC3339) {
  96. t.Errorf("UpdatedAt be using the nowFuncOverride")
  97. }
  98. // now create another user with a fresh DB.Now() that doesn't have the nowFuncOverride set
  99. // to make sure that setting it only affected the above instance
  100. user2 := User{Name: "CreateUserTimestampOverrideNoMore"}
  101. db2 := DB.New()
  102. db2.Save(&user2)
  103. if user2.CreatedAt.UTC().Format(time.RFC3339) == timeA.UTC().Format(time.RFC3339) {
  104. t.Errorf("CreatedAt no longer be using the nowFuncOverride")
  105. }
  106. if user2.UpdatedAt.UTC().Format(time.RFC3339) == timeA.UTC().Format(time.RFC3339) {
  107. t.Errorf("UpdatedAt no longer be using the nowFuncOverride")
  108. }
  109. }
  110. type AutoIncrementUser struct {
  111. User
  112. Sequence uint `gorm:"AUTO_INCREMENT"`
  113. }
  114. func TestCreateWithAutoIncrement(t *testing.T) {
  115. if dialect := os.Getenv("GORM_DIALECT"); dialect != "postgres" {
  116. t.Skip("Skipping this because only postgres properly support auto_increment on a non-primary_key column")
  117. }
  118. DB.AutoMigrate(&AutoIncrementUser{})
  119. user1 := AutoIncrementUser{}
  120. user2 := AutoIncrementUser{}
  121. DB.Create(&user1)
  122. DB.Create(&user2)
  123. if user2.Sequence-user1.Sequence != 1 {
  124. t.Errorf("Auto increment should apply on Sequence")
  125. }
  126. }
  127. func TestCreateWithNoGORMPrimayKey(t *testing.T) {
  128. if dialect := os.Getenv("GORM_DIALECT"); dialect == "mssql" {
  129. t.Skip("Skipping this because MSSQL will return identity only if the table has an Id column")
  130. }
  131. jt := JoinTable{From: 1, To: 2}
  132. err := DB.Create(&jt).Error
  133. if err != nil {
  134. t.Errorf("No error should happen when create a record without a GORM primary key. But in the database this primary key exists and is the union of 2 or more fields\n But got: %s", err)
  135. }
  136. }
  137. func TestCreateWithNoStdPrimaryKeyAndDefaultValues(t *testing.T) {
  138. animal := Animal{Name: "Ferdinand"}
  139. if DB.Save(&animal).Error != nil {
  140. t.Errorf("No error should happen when create a record without std primary key")
  141. }
  142. if animal.Counter == 0 {
  143. t.Errorf("No std primary key should be filled value after create")
  144. }
  145. if animal.Name != "Ferdinand" {
  146. t.Errorf("Default value should be overrided")
  147. }
  148. // Test create with default value not overrided
  149. an := Animal{From: "nerdz"}
  150. if DB.Save(&an).Error != nil {
  151. t.Errorf("No error should happen when create an record without std primary key")
  152. }
  153. // We must fetch the value again, to have the default fields updated
  154. // (We can't do this in the update statements, since sql default can be expressions
  155. // And be different from the fields' type (eg. a time.Time fields has a default value of "now()"
  156. DB.Model(Animal{}).Where(&Animal{Counter: an.Counter}).First(&an)
  157. if an.Name != "galeone" {
  158. t.Errorf("Default value should fill the field. But got %v", an.Name)
  159. }
  160. }
  161. func TestAnonymousScanner(t *testing.T) {
  162. user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}}
  163. DB.Save(&user)
  164. var user2 User
  165. DB.First(&user2, "name = ?", "anonymous_scanner")
  166. if user2.Role.Name != "admin" {
  167. t.Errorf("Should be able to get anonymous scanner")
  168. }
  169. if !user2.Role.IsAdmin() {
  170. t.Errorf("Should be able to get anonymous scanner")
  171. }
  172. }
  173. func TestAnonymousField(t *testing.T) {
  174. user := User{Name: "anonymous_field", Company: Company{Name: "company"}}
  175. DB.Save(&user)
  176. var user2 User
  177. DB.First(&user2, "name = ?", "anonymous_field")
  178. DB.Model(&user2).Related(&user2.Company)
  179. if user2.Company.Name != "company" {
  180. t.Errorf("Should be able to get anonymous field")
  181. }
  182. }
  183. func TestSelectWithCreate(t *testing.T) {
  184. user := getPreparedUser("select_user", "select_with_create")
  185. DB.Select("Name", "BillingAddress", "CreditCard", "Company", "Emails").Create(user)
  186. var queryuser User
  187. DB.Preload("BillingAddress").Preload("ShippingAddress").
  188. Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryuser, user.Id)
  189. if queryuser.Name != user.Name || queryuser.Age == user.Age {
  190. t.Errorf("Should only create users with name column")
  191. }
  192. if queryuser.BillingAddressID.Int64 == 0 || queryuser.ShippingAddressId != 0 ||
  193. queryuser.CreditCard.ID == 0 || len(queryuser.Emails) == 0 {
  194. t.Errorf("Should only create selected relationships")
  195. }
  196. }
  197. func TestOmitWithCreate(t *testing.T) {
  198. user := getPreparedUser("omit_user", "omit_with_create")
  199. DB.Omit("Name", "BillingAddress", "CreditCard", "Company", "Emails").Create(user)
  200. var queryuser User
  201. DB.Preload("BillingAddress").Preload("ShippingAddress").
  202. Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryuser, user.Id)
  203. if queryuser.Name == user.Name || queryuser.Age != user.Age {
  204. t.Errorf("Should only create users with age column")
  205. }
  206. if queryuser.BillingAddressID.Int64 != 0 || queryuser.ShippingAddressId == 0 ||
  207. queryuser.CreditCard.ID != 0 || len(queryuser.Emails) != 0 {
  208. t.Errorf("Should not create omitted relationships")
  209. }
  210. }
  211. func TestCreateIgnore(t *testing.T) {
  212. float := 35.03554004971999
  213. now := time.Now()
  214. user := User{Name: "CreateUser", Age: 18, Birthday: &now, UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float}
  215. if !DB.NewRecord(user) || !DB.NewRecord(&user) {
  216. t.Error("User should be new record before create")
  217. }
  218. if count := DB.Create(&user).RowsAffected; count != 1 {
  219. t.Error("There should be one record be affected when create record")
  220. }
  221. if DB.Dialect().GetName() == "mysql" && DB.Set("gorm:insert_modifier", "IGNORE").Create(&user).Error != nil {
  222. t.Error("Should ignore duplicate user insert by insert modifier:IGNORE ")
  223. }
  224. }