-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdb.go
More file actions
44 lines (33 loc) · 1.08 KB
/
db.go
File metadata and controls
44 lines (33 loc) · 1.08 KB
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
package main
import (
"database/sql"
"fmt"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/joho/godotenv"
)
func InitDatabase(dotenvPath string) (*sql.DB, error) {
err := godotenv.Load(dotenvPath)
if err != nil {return nil, err}
dbUser := os.Getenv("DB_USER")
dbPass := os.Getenv("DB_PASS")
dbName := os.Getenv("DB_NAME")
dbURL := fmt.Sprintf("%s:%s@/", dbUser, dbPass)
db, err := sql.Open("mysql", dbURL)
if err != nil {return nil, err}
// Check if the database exists
rows, err := db.Query("SHOW DATABASES LIKE " + fmt.Sprintf(`"%s"`, dbName))
if err != nil {return nil, err}
defer rows.Close()
if !rows.Next() {
// Create the database if it doesn't exist
_, err := db.Exec("CREATE DATABASE " + dbName)
if err != nil {return nil, err}
}
// Close the current connection and reconnect to the specific database
db.Close()
dbURLWithDbName:= fmt.Sprintf("%s:%s@/%s", dbUser, dbPass, dbName)
db, err = sql.Open("mysql", dbURLWithDbName)
if err != nil {return nil, err}
return db, nil
}