src/app/init.go (view raw)
1package app
2
3import (
4 "log"
5 "os"
6 "path"
7
8 "github.com/glebarez/sqlite"
9 "gorm.io/gorm"
10)
11
12const (
13 dbDir = "data"
14 sqliteSuffix = "?_pragma=foreign_keys(1)"
15)
16
17var DB *gorm.DB
18
19func InitDB() {
20 err := os.MkdirAll(dbDir, os.ModePerm)
21 if err != nil {
22 log.Println(err) // do not return here
23 }
24
25 dsn := path.Join(dbDir, "data.sqlite") + sqliteSuffix
26
27 DB, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
28 if err != nil {
29 log.Fatal("Failed to connect to database: ", err)
30 }
31
32 // Migrate schema
33 err = DB.AutoMigrate(&Bookmaker{}, &Account{}, &Record{}, &Entry{}, &SubEntry{})
34 if err != nil {
35 log.Fatal(err)
36 }
37
38 var bookmakersAmount int64
39 err = DB.Model(&Bookmaker{}).Count(&bookmakersAmount).Error
40 if err != nil {
41 log.Println("could not count bookmakers: " + err.Error())
42 }
43 if bookmakersAmount == 0 {
44 err = DB.Create(&Bookmaker{Name: "Test"}).Error
45 if err != nil {
46 log.Fatal(err)
47 }
48 err = DB.Create(&Bookmaker{Name: "Test 2"}).Error
49 if err != nil {
50 log.Fatal(err)
51 }
52 err = DB.Create(&Bookmaker{Name: "Test Exchange", Exchange: true}).Error
53 if err != nil {
54 log.Fatal(err)
55 }
56 }
57
58 err = DB.Model(&Bookmaker{}).Where(&Bookmaker{Exchange: true}).Pluck("id", &ExchangeIDs).Error
59 if err != nil {
60 log.Println("could not get exchange ids: " + err.Error())
61 }
62}