-
Notifications
You must be signed in to change notification settings - Fork 2
/
sources.go
48 lines (40 loc) · 1.1 KB
/
sources.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package goseeder
import (
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"io/ioutil"
"log"
)
var dataPath = "db/seeds/data"
//SetDataPath this will allow you to specify a custom path where your seed data is located
func SetDataPath(path string) {
dataPath = path
}
//FromJson inserts into a database table with name same as the filename all the json entries
func (s Seeder) FromJson(filename string) {
s.fromJson(filename, filename)
}
//FromJsonIntoTable reads json from the given file and inserts into the given table name
func (s Seeder) FromJsonIntoTable(filename string, tableName string) {
s.fromJson(filename, tableName)
}
func (s Seeder) fromJson(filename string, tableName string) {
content, err := ioutil.ReadFile(fmt.Sprintf("%s/%s.json", dataPath, filename))
if err != nil {
log.Fatal(err)
}
m := []map[string]interface{}{}
err = json.Unmarshal(content, &m)
if err != nil {
panic(err)
}
for _, e := range m {
stmQuery, args := prepareStatement(tableName, e)
stmt, _ := s.DB.Prepare(stmQuery.String())
_, err := stmt.Exec(args...)
if err != nil {
panic(err)
}
}
}