forked from andey-robins/bookshop-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
46 lines (37 loc) · 789 Bytes
/
db.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
package db
import (
"database/sql"
"log"
"os"
"sync"
_ "github.com/mattn/go-sqlite3"
)
type Database struct {
Db *sql.DB
}
var instance *Database
var once sync.Once
func Connect() *Database {
once.Do(func() {
mustCreateDb := false
if _, err := os.Stat("dd.db"); err != nil {
mustCreateDb = true
}
database, err := sql.Open("sqlite3", "dd.db")
if err != nil {
log.Fatalf("Error connecting to database: %v", err)
}
if mustCreateDb {
if command, err := os.ReadFile("init.sql"); err == nil {
_, err := database.Exec(string(command))
if err != nil {
log.Fatalf("Error initializing database: %v", err)
}
} else {
log.Fatalf("Error loading sqlite initial schema")
}
}
instance = &Database{Db: database}
})
return instance
}