Skip to content

Commit e9ae08e

Browse files
committed
Create empty db if does not exist
1 parent e947eb8 commit e9ae08e

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ build:
55
go build -o ./dist/dsync ./main.go
66
chmod +x ./dist/dsync
77

8+
local:
9+
go build -o $(GOBIN)/dsync ./main.go
10+
chmod +x $(GOBIN)/dsync
11+
812
install:
913
go install github.com/asolopovas/dsync@latest
1014

src/libs.go

+37-3
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,43 @@ func DumpRemoteDB(config JsonConfig) ([]byte, error) {
108108
return stdout.Bytes(), err
109109
}
110110

111+
func createUserAndDB(dbName string, confLoc string) {
112+
fmt.Println("Creating emptry db: `" + dbName + "` if does not exist ...")
113+
114+
query := fmt.Sprintf(
115+
"CREATE USER IF NOT EXISTS `%s`@'%%' IDENTIFIED BY 'secret'; "+
116+
"CREATE DATABASE IF NOT EXISTS `%s`; "+
117+
"GRANT ALL PRIVILEGES ON `%s`.* TO `%s`@'%%';",
118+
dbName, dbName, dbName, dbName,
119+
)
120+
121+
args := []string{
122+
"compose",
123+
"-f", confLoc,
124+
"exec",
125+
"-T",
126+
"mariadb",
127+
"mariadb",
128+
"-uroot",
129+
"-psecret",
130+
"-e",
131+
query,
132+
}
133+
134+
cmd := exec.Command("docker", args...)
135+
cmd.Stdout = os.Stdout
136+
cmd.Stderr = os.Stderr
137+
if err := cmd.Run(); err != nil {
138+
fmt.Println("Error:", err)
139+
}
140+
}
141+
111142
func WriteToLocalDB(sqlDumpStr string, conf JsonConfig, dumpDb bool) {
112143
fmt.Println("Writing to local DB")
144+
confLoc := os.Getenv("HOME") + "/www/dev/docker-compose.yml"
145+
146+
createUserAndDB(conf.Local.Db, confLoc)
147+
113148
sqlDump := []byte(sqlDumpStr)
114149
var stdin bytes.Buffer
115150
stdin.Write(sqlDump)
@@ -119,14 +154,13 @@ func WriteToLocalDB(sqlDumpStr string, conf JsonConfig, dumpDb bool) {
119154
os.WriteFile("db.sql", sqlDump, 0644)
120155
}
121156

122-
os.Chdir(os.Getenv("HOME") + "/www/dev")
123-
124157
args := []string{
125158
"compose",
159+
"-f", confLoc,
126160
"exec",
127161
"-T",
128162
"mariadb",
129-
"mysql",
163+
"mariadb",
130164
"-uroot",
131165
"-psecret",
132166
conf.Local.Db,

0 commit comments

Comments
 (0)