This repository has been archived by the owner on Oct 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmysqlseed.go
55 lines (46 loc) · 1.7 KB
/
mysqlseed.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
49
50
51
52
53
54
55
package mysqlseed
import (
"bytes"
"database/sql"
"fmt"
"io/ioutil"
"os/exec"
"strings"
)
// ApplySeedWithCmd loads a seed sql file and executes it against the db.
// expects hostnameAndPort to be on the form `127.0.0.1:3306`
// Requires MySQL Command-Line Tool to be installed
func ApplySeedWithCmd(hostnameAndPort string, dbUser string, dbPass string, dbName string, seedFilePath string) error {
instanceHostAndPort := strings.Split(hostnameAndPort, ":")
hostName := instanceHostAndPort[0]
if hostName == "localhost" {
hostName = "127.0.0.1"
}
hostPort := instanceHostAndPort[1]
var cmd *exec.Cmd = nil
if dbPass == "" {
cmd = exec.Command("mysql", fmt.Sprintf("-h%s", hostName), fmt.Sprintf("-u%s", dbUser), fmt.Sprintf("-P%s", hostPort), dbName, "-e", fmt.Sprintf("source %s", seedFilePath))
} else {
cmd = exec.Command("mysql", fmt.Sprintf("-h%s", hostName), fmt.Sprintf("-u%s", dbUser), fmt.Sprintf("-p%s", dbPass), fmt.Sprintf("-P%s", hostPort), dbName, "-e", fmt.Sprintf("source %s", seedFilePath))
}
cmd.Stdout = &bytes.Buffer{}
cmd.Stderr = &bytes.Buffer{}
err := cmd.Run()
if err != nil {
return fmt.Errorf("error executing query.\nCommand Stdout: %+v\nCommand Stderr: %+v\nError: %v", cmd.Stdout, cmd.Stderr, err)
}
return nil
}
// ApplySeedWithDB loads a seed sql file and executes it against the db.
// Requires MySQL connection to use `multiStatements=true`
func ApplySeedWithDB(db *sql.DB, seedFilePath string) error {
fileBytes, err := ioutil.ReadFile(seedFilePath)
if err != nil {
return fmt.Errorf("could not read seed-file.\nError: %v", err)
}
_, err = db.Exec(string(fileBytes))
if err != nil {
return fmt.Errorf("could not apply seed.\nError: %v", err)
}
return nil
}