-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
170 lines (149 loc) · 3.25 KB
/
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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package main
import (
"context"
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
// DB should be constructed with NewDB.
type DB struct {
client *sql.DB
}
// NewDB conditionally initializes our database for demo purposes, returning a DB with
// the methods intended for use by other layers.
func NewDB(filepath string, initData bool) DB {
client := InitDB(filepath)
if initData {
InitTables(client)
InitReferenceData(client)
}
db := DB{client}
return db
}
// InitDB prepares a DB connection. For an in-memory instance instead of a file,
// use ":memory:?cache=shared" as the filepath.
func InitDB(filepath string) *sql.DB {
client, err := sql.Open("sqlite3", filepath)
if err != nil {
panic(err)
}
if client == nil {
panic("Failed to create or open db")
}
return client
}
// InitTables is provided for demo convenience. A real app shouldn't do this.
func InitTables(db *sql.DB) {
tables := []string{`
CREATE TABLE IF NOT EXISTS instrument(
instrument_id INTEGER PRIMARY KEY,
description TEXT NOT NULL
);
`, `
CREATE TABLE IF NOT EXISTS run_instrument(
run_id INTEGER PRIMARY KEY,
instrument_id INTEGER NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(instrument_id) REFERENCES instrument(instrument_id)
);
`, `
CREATE TABLE IF NOT EXISTS run_sample(
sample_id INTEGER,
run_id INTEGER,
FOREIGN KEY(run_id) REFERENCES run_instrument(run_id)
PRIMARY KEY(sample_id, run_id)
);
`}
for _, t := range tables {
fmt.Println(t)
_, err := db.Exec(t)
if err != nil {
panic(err)
}
}
}
// InitReferenceData is provided for demo convenience. A real app shouldn't do this.
func InitReferenceData(db *sql.DB) {
instruments := [3]string{"Instrument 1", "Instrument 2", "Instrument 3"}
sql := `
INSERT INTO instrument(
description
) VALUES (?);
`
statement, err := db.Prepare(sql)
if err != nil {
panic(err)
}
defer statement.Close()
for _, item := range instruments {
_, err := statement.Exec(item)
if err != nil {
panic(err)
}
}
}
// SaveRun returns the newly generated run ID.
func (db DB) SaveRun(run Run) (int, error) {
tx, err := db.client.BeginTx(context.TODO(), nil)
if err != nil {
log.Println(err)
}
sql := `
INSERT INTO run_instrument(
instrument_id
) VALUES (?);
`
runStatement, err := tx.Prepare(sql)
if err != nil {
log.Println(err)
tx.Rollback()
return 0, err
}
defer runStatement.Close()
_, err = runStatement.Exec(run.InstrumentID)
if err != nil {
log.Println(err)
tx.Rollback()
return 0, err
}
// Use sqlite's somewhat awkward last_insert_rowid() for retrieving our new run_id.
sql = "SELECT last_insert_rowid() AS id"
rows, err := tx.Query(sql)
if err != nil {
tx.Rollback()
return 0, err
}
var runID int
defer rows.Close()
for rows.Next() {
err := rows.Scan(&runID)
if err != nil {
tx.Rollback()
return 0, err
}
}
sql = `
INSERT INTO run_sample(
sample_id,
run_id
) VALUES (?, ?);
`
sampleStatement, err := tx.Prepare(sql)
if err != nil {
log.Println(err)
tx.Rollback()
return 0, err
}
defer sampleStatement.Close()
for _, s := range run.Samples {
_, err = sampleStatement.Exec(s.ID, runID)
if err != nil {
log.Println(err)
tx.Rollback()
return 0, err
}
}
tx.Commit()
return runID, nil
}