Skip to content

Commit

Permalink
test(sql_builder_test): add two test for CreateInBatches
Browse files Browse the repository at this point in the history
  • Loading branch information
Anton Kichaev committed Sep 2, 2023
1 parent 28331bf commit 05cc9cf
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion tests/sql_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,51 @@ func TestToSQL(t *testing.T) {
})
})
assertEqualSQL(t, `SELECT * FROM users ORDER BY id DESC`, sql)

// create batch, models are equal batch size
bs := 2
m := gorm.Model{
CreatedAt: date,
UpdatedAt: date,
}
sql = DB.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Model(&User{}).
CreateInBatches(
[]User{
{
Name: "foo", Age: 20, Model: m,
},
{
Name: "bar", Age: 30, Model: m,
},
},
bs,
)
})
assertEqualSQL(t, `INSERT INTO "users" ("created_at","updated_at","deleted_at","name","age","birthday","company_id","manager_id","active") VALUES ('2021-10-18 00:00:00','2021-10-18 00:00:00',NULL,'foo',20,NULL,NULL,NULL,false),('2021-10-18 00:00:00','2021-10-18 00:00:00',NULL,'bar',30,NULL,NULL,NULL,false) RETURNING "id";`, sql)

// create batch models are more than batch size
sql = DB.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Model(&User{}).
CreateInBatches(
[]User{
{
Name: "foo", Age: 20, Model: m,
},
{
Name: "bar", Age: 30, Model: m,
},
{
Name: "foo bar", Age: 40, Model: m,
},
{
Name: "bar foo", Age: 50, Model: m,
},
},
bs,
)
})
assertEqualSQL(t, `INSERT INTO "users" ("created_at","updated_at","deleted_at","name","age","birthday","company_id","manager_id","active") VALUES ('2021-10-18 00:00:00','2021-10-18 00:00:00',NULL,'foo',20,NULL,NULL,NULL,false),('2021-10-18 00:00:00','2021-10-18 00:00:00',NULL,'bar',30,NULL,NULL,NULL,false) RETURNING "id";INSERT INTO "users" ("created_at","updated_at","deleted_at","name","age","birthday","company_id","manager_id","active") VALUES ('2021-10-18 00:00:00','2021-10-18 00:00:00',NULL,'foo bar',40,NULL,NULL,NULL,false),('2021-10-18 00:00:00','2021-10-18 00:00:00',NULL,'bar foo',50,NULL,NULL,NULL,false) RETURNING "id";`, sql)
}

// assertEqualSQL for assert that the sql is equal, this method will ignore quote, and dialect specials.
Expand All @@ -469,7 +514,7 @@ func assertEqualSQL(t *testing.T, expected string, actually string) {
expected = updatedAtRe.ReplaceAllString(expected, `"updated_at"=?`)

// ignore RETURNING "id" (only in PostgreSQL)
returningRe := regexp.MustCompile(`(?i)RETURNING "id"`)
returningRe := regexp.MustCompile(`\s?(?i)RETURNING "id"`)
actually = returningRe.ReplaceAllString(actually, ``)
expected = returningRe.ReplaceAllString(expected, ``)

Expand Down

0 comments on commit 05cc9cf

Please sign in to comment.