forked from go-jet/jet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
124 lines (98 loc) · 2.32 KB
/
init.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"database/sql"
"flag"
"fmt"
"github.com/go-jet/jet/generator/mysql"
"github.com/go-jet/jet/generator/postgres"
"github.com/go-jet/jet/internal/utils"
"github.com/go-jet/jet/tests/dbconfig"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
"io/ioutil"
"os"
"os/exec"
"strings"
)
var testSuite string
func init() {
flag.StringVar(&testSuite, "testsuite", "all", "Test suite name (postgres or mysql)")
flag.Parse()
}
func main() {
testSuite = strings.ToLower(testSuite)
if testSuite == "postgres" {
initPostgresDB()
return
}
if testSuite == "mysql" || testSuite == "mariadb" {
initMySQLDB()
return
}
initMySQLDB()
initPostgresDB()
}
func initMySQLDB() {
mySQLDBs := []string{
"dvds",
"test_sample",
}
for _, dbName := range mySQLDBs {
cmdLine := fmt.Sprintf("mysql -h 127.0.0.1 -u %s -p%s %s < %s",
dbconfig.MySQLUser, dbconfig.MySQLPassword, dbName, "./testdata/init/mysql/"+dbName+".sql")
fmt.Println(cmdLine)
cmd := exec.Command("sh", "-c", cmdLine)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
err := cmd.Run()
utils.PanicOnError(err)
err = mysql.Generate("./.gentestdata/mysql", mysql.DBConnection{
Host: dbconfig.MySqLHost,
Port: dbconfig.MySQLPort,
User: dbconfig.MySQLUser,
Password: dbconfig.MySQLPassword,
DBName: dbName,
})
utils.PanicOnError(err)
}
}
func initPostgresDB() {
db, err := sql.Open("postgres", dbconfig.PostgresConnectString)
if err != nil {
panic("Failed to connect to test db")
}
defer func() {
err := db.Close()
printOnError(err)
}()
schemaNames := []string{
"dvds",
"test_sample",
"chinook",
"northwind",
}
for _, schemaName := range schemaNames {
execFile(db, "./testdata/init/postgres/"+schemaName+".sql")
err = postgres.Generate("./.gentestdata", postgres.DBConnection{
Host: dbconfig.Host,
Port: 5432,
User: dbconfig.User,
Password: dbconfig.Password,
DBName: dbconfig.DBName,
SchemaName: schemaName,
SslMode: "disable",
})
utils.PanicOnError(err)
}
}
func execFile(db *sql.DB, sqlFilePath string) {
testSampleSql, err := ioutil.ReadFile(sqlFilePath)
utils.PanicOnError(err)
_, err = db.Exec(string(testSampleSql))
utils.PanicOnError(err)
}
func printOnError(err error) {
if err != nil {
fmt.Println(err.Error())
}
}