This repository has been archived by the owner on Aug 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
currency.go
108 lines (91 loc) · 2.55 KB
/
currency.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package models
import (
"database/sql"
"time"
)
// InitCurrency initiliazes the tables needed for the currency system.
func InitCurrency(db *sql.DB) error {
_, err := db.Exec("CREATE TABLE IF NOT EXISTS `Currency` (" +
"`UserID` TEXT NOT NULL PRIMARY KEY UNIQUE," +
"`Amount` INTEGER NOT NULL" +
")")
if err != nil {
return err
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS `CurrencyTransactions` (" +
"`ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
"`Amount` INTEGER NOT NULL," +
"`Reason` TEXT NOT NULL," +
"`UserID` TEXT NOT NULL," +
"`DateAdded` INTEGER NOT NULL" +
")")
if err != nil {
return err
}
return nil
}
// Currency is the type for holding currency info about a user.
type Currency struct {
UserID string
Amount int
DateAdded int
}
// CreateCurrency creates and inserts a Currency.
func CreateCurrency(db *sql.DB, amount int, userID string) (*Currency, error) {
stmt, err := db.Prepare("INSERT INTO Currency (Amount, UserID, DateAdded) values(?,?,?)")
if err != nil {
return nil, err
}
dateAdded := int(time.Now().Unix())
_, err = stmt.Exec(amount, userID, dateAdded)
if err != nil {
return nil, err
}
return &Currency{
UserID: userID,
Amount: amount,
DateAdded: dateAdded,
}, nil
}
// GetCurrency returns a specific currency
func GetCurrency(db *sql.DB, userID string) (*Currency, error) {
currency := &Currency{}
err := db.QueryRow("SELECT * FROM Currency WHERE userID =?", userID).Scan(¤cy.UserID, ¤cy.Amount, ¤cy.DateAdded)
if err != nil {
return nil, err
}
return currency, nil
}
// CurrencyTransaction is the type for keeping track of a transaction to a
// currency type.
type CurrencyTransaction struct {
ID int
Amount int
UserID string
Reason string
DateAdded int
}
// CreateCurrencyTransaction will create and insert a new CurrencyTransaction.
func CreateCurrencyTransaction(db *sql.DB, amount int, userID, reason string) (*CurrencyTransaction, error) {
stmt, err := db.Prepare("INSERT INTO CurrencyTransaction (Amount, UserID, Reason, DateAdded) values (?,?,?,?)")
if err != nil {
return nil, err
}
dateAdded := int(time.Now().Unix())
_, err = stmt.Exec(amount, userID, reason, dateAdded)
if err != nil {
return nil, err
}
id := 0
err = db.QueryRow("SELECT ID FROM CurrencyTransaction WHERE UserID =? AND WHERE DateAdded =?", userID, dateAdded).Scan(&id)
if err != nil {
return nil, err
}
return &CurrencyTransaction{
ID: id,
Amount: amount,
UserID: userID,
Reason: reason,
DateAdded: dateAdded,
}, nil
}