File tree Expand file tree Collapse file tree 1 file changed +15
-3
lines changed Expand file tree Collapse file tree 1 file changed +15
-3
lines changed Original file line number Diff line number Diff line change 1
1
package database
2
2
3
3
import (
4
+ "errors"
4
5
"fmt"
5
6
"io/ioutil"
6
7
@@ -9,19 +10,30 @@ import (
9
10
10
11
// MustApplyDatabaseSeed applies all SQL queries from the given file to the currently active database.
11
12
// 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
+
13
24
applySeedCheckSQL := `
14
25
SELECT
15
26
SUM(TABLE_ROWS) AS rows
16
27
FROM
17
28
information_schema.TABLES
18
29
WHERE
19
- TABLE_SCHEMA = ? AND TABLE_NAME NOT IN ('schema_migrations')
30
+ TABLE_SCHEMA = ? AND TABLE_NAME NOT IN ?
20
31
`
21
32
result := struct {
22
33
Rows uint64
23
34
}{}
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 {
25
37
panic (fmt .Errorf ("failed to check whether seed should be applied: %w" , err ))
26
38
}
27
39
You can’t perform that action at this time.
0 commit comments