all repos — piggy @ aac7712a4650e29b43bbaec3b3ac295214a16367

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	err = DB.Model(&Bookmaker{}).Where("default_commission > 0").Pluck("id", &ExchangeIDs).Error
48	if err != nil {
49		log.Println("could not get exchange ids: " + err.Error())
50	}
51}
52
53func InsertSampleData() {
54	err := DB.Create(&Bookmaker{Name: "First Bookmaker"}).Error
55	if err != nil {
56		log.Fatal(err)
57	}
58	err = DB.Create(&Bookmaker{Name: "Second Bookmaker"}).Error
59	if err != nil {
60		log.Fatal(err)
61	}
62	err = DB.Create(&Bookmaker{Name: "Third Exchange", DefaultCommission: 450}).Error
63	if err != nil {
64		log.Fatal(err)
65	}
66
67	err = DB.Create(&Account{Name: "First Account"}).Error
68	if err != nil {
69		log.Fatal(err)
70	}
71	err = DB.Create(&Account{Name: "Second Account"}).Error
72	if err != nil {
73		log.Fatal(err)
74	}
75}