Skip to content

Commit 03864a4

Browse files
committed
allow exceptions in MustApplyDatabaseSeed check
1 parent 68345e5 commit 03864a4

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

database/seed.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package database
22

33
import (
4+
"errors"
45
"fmt"
56
"io/ioutil"
67

@@ -9,19 +10,30 @@ import (
910

1011
// MustApplyDatabaseSeed applies all SQL queries from the given file to the currently active database.
1112
// If any database table besides "schema_migrations" already contains data, the seed file will not be applied.
12-
func MustApplyDatabaseSeed(file string, db *gorm.DB) {
13+
// The third argument is optional and can be used to exclude tables from checking whether data is already seeded or not.
14+
func MustApplyDatabaseSeed(file string, db *gorm.DB, excludedTables ...[]string) {
15+
if len(excludedTables) > 1 {
16+
panic(errors.New("not more than 3 arguments allowed"))
17+
}
18+
19+
excludedTablesInSQL := []string{"schema_migrations"}
20+
if len(excludedTables) == 1 {
21+
excludedTablesInSQL = append(excludedTablesInSQL, excludedTables[0]...)
22+
}
23+
1324
applySeedCheckSQL := `
1425
SELECT
1526
SUM(TABLE_ROWS) AS rows
1627
FROM
1728
information_schema.TABLES
1829
WHERE
19-
TABLE_SCHEMA = ? AND TABLE_NAME NOT IN ('schema_migrations')
30+
TABLE_SCHEMA = ? AND TABLE_NAME NOT IN ?
2031
`
2132
result := struct {
2233
Rows uint64
2334
}{}
24-
if err := db.Raw(applySeedCheckSQL, db.Migrator().CurrentDatabase()).Scan(&result).Error; err != nil {
35+
statement := db.Raw(applySeedCheckSQL, db.Migrator().CurrentDatabase(), excludedTablesInSQL)
36+
if err := statement.Scan(&result).Error; err != nil {
2537
panic(fmt.Errorf("failed to check whether seed should be applied: %w", err))
2638
}
2739

0 commit comments

Comments
 (0)