all repos — piggy @ 0.0.1

Dead simple finance manager in Go, HTML and JS.

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		InsertSampleData()
45	}
46}
47
48func InsertSampleData() {
49	err := DB.Create(&Bookmaker{Name: "First Bookmaker"}).Error
50	if err != nil {
51		log.Fatal(err)
52	}
53	err = DB.Create(&Bookmaker{Name: "Second Bookmaker"}).Error
54	if err != nil {
55		log.Fatal(err)
56	}
57	err = DB.Create(&Bookmaker{Name: "Third Exchange", DefaultCommission: 450}).Error
58	if err != nil {
59		log.Fatal(err)
60	}
61
62	err = DB.Create(&Account{Name: "First Account"}).Error
63	if err != nil {
64		log.Fatal(err)
65	}
66	err = DB.Create(&Account{Name: "Second Account"}).Error
67	if err != nil {
68		log.Fatal(err)
69	}
70}