create_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. type AutoIncrementUser struct {
  81. User
  82. Sequence uint `gorm:"AUTO_INCREMENT"`
  83. }
  84. func TestCreateWithAutoIncrement(t *testing.T) {
  85. if dialect := os.Getenv("GORM_DIALECT"); dialect != "postgres" {
  86. t.Skip("Skipping this because only postgres properly support auto_increment on a non-primary_key column")
  87. }
  88. DB.AutoMigrate(&AutoIncrementUser{})
  89. user1 := AutoIncrementUser{}
  90. user2 := AutoIncrementUser{}
  91. DB.Create(&user1)
  92. DB.Create(&user2)
  93. if user2.Sequence-user1.Sequence != 1 {
  94. t.Errorf("Auto increment should apply on Sequence")
  95. }
  96. }
  97. func TestCreateWithNoGORMPrimayKey(t *testing.T) {
  98. if dialect := os.Getenv("GORM_DIALECT"); dialect == "mssql" {
  99. t.Skip("Skipping this because MSSQL will return identity only if the table has an Id column")
  100. }
  101. jt := JoinTable{From: 1, To: 2}
  102. err := DB.Create(&jt).Error
  103. if err != nil {
  104. 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)
  105. }
  106. }
  107. func TestCreateWithNoStdPrimaryKeyAndDefaultValues(t *testing.T) {
  108. animal := Animal{Name: "Ferdinand"}
  109. if DB.Save(&animal).Error != nil {
  110. t.Errorf("No error should happen when create a record without std primary key")
  111. }
  112. if animal.Counter == 0 {
  113. t.Errorf("No std primary key should be filled value after create")
  114. }
  115. if animal.Name != "Ferdinand" {
  116. t.Errorf("Default value should be overrided")
  117. }
  118. // Test create with default value not overrided
  119. an := Animal{From: "nerdz"}
  120. if DB.Save(&an).Error != nil {
  121. t.Errorf("No error should happen when create an record without std primary key")
  122. }
  123. // We must fetch the value again, to have the default fields updated
  124. // (We can't do this in the update statements, since sql default can be expressions
  125. // And be different from the fields' type (eg. a time.Time fields has a default value of "now()"
  126. DB.Model(Animal{}).Where(&Animal{Counter: an.Counter}).First(&an)
  127. if an.Name != "galeone" {
  128. t.Errorf("Default value should fill the field. But got %v", an.Name)
  129. }
  130. }
  131. func TestAnonymousScanner(t *testing.T) {
  132. user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}}
  133. DB.Save(&user)
  134. var user2 User
  135. DB.First(&user2, "name = ?", "anonymous_scanner")
  136. if user2.Role.Name != "admin" {
  137. t.Errorf("Should be able to get anonymous scanner")
  138. }
  139. if !user2.Role.IsAdmin() {
  140. t.Errorf("Should be able to get anonymous scanner")
  141. }
  142. }
  143. func TestAnonymousField(t *testing.T) {
  144. user := User{Name: "anonymous_field", Company: Company{Name: "company"}}
  145. DB.Save(&user)
  146. var user2 User
  147. DB.First(&user2, "name = ?", "anonymous_field")
  148. DB.Model(&user2).Related(&user2.Company)
  149. if user2.Company.Name != "company" {
  150. t.Errorf("Should be able to get anonymous field")
  151. }
  152. }
  153. func TestSelectWithCreate(t *testing.T) {
  154. user := getPreparedUser("select_user", "select_with_create")
  155. DB.Select("Name", "BillingAddress", "CreditCard", "Company", "Emails").Create(user)
  156. var queryuser User
  157. DB.Preload("BillingAddress").Preload("ShippingAddress").
  158. Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryuser, user.Id)
  159. if queryuser.Name != user.Name || queryuser.Age == user.Age {
  160. t.Errorf("Should only create users with name column")
  161. }
  162. if queryuser.BillingAddressID.Int64 == 0 || queryuser.ShippingAddressId != 0 ||
  163. queryuser.CreditCard.ID == 0 || len(queryuser.Emails) == 0 {
  164. t.Errorf("Should only create selected relationships")
  165. }
  166. }
  167. func TestOmitWithCreate(t *testing.T) {
  168. user := getPreparedUser("omit_user", "omit_with_create")
  169. DB.Omit("Name", "BillingAddress", "CreditCard", "Company", "Emails").Create(user)
  170. var queryuser User
  171. DB.Preload("BillingAddress").Preload("ShippingAddress").
  172. Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryuser, user.Id)
  173. if queryuser.Name == user.Name || queryuser.Age != user.Age {
  174. t.Errorf("Should only create users with age column")
  175. }
  176. if queryuser.BillingAddressID.Int64 != 0 || queryuser.ShippingAddressId == 0 ||
  177. queryuser.CreditCard.ID != 0 || len(queryuser.Emails) != 0 {
  178. t.Errorf("Should not create omitted relationships")
  179. }
  180. }
  181. func TestCreateIgnore(t *testing.T) {
  182. float := 35.03554004971999
  183. now := time.Now()
  184. user := User{Name: "CreateUser", Age: 18, Birthday: &now, UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float}
  185. if !DB.NewRecord(user) || !DB.NewRecord(&user) {
  186. t.Error("User should be new record before create")
  187. }
  188. if count := DB.Create(&user).RowsAffected; count != 1 {
  189. t.Error("There should be one record be affected when create record")
  190. }
  191. if DB.Dialect().GetName() == "mysql" && DB.Set("gorm:insert_modifier", "IGNORE").Create(&user).Error != nil {
  192. t.Error("Should ignore duplicate user insert by insert modifier:IGNORE ")
  193. }
  194. }