-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.go
386 lines (360 loc) · 10.6 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package songmem
import (
"database/sql"
"errors"
sqlite3 "github.com/mattn/go-sqlite3"
"time"
)
type SongDB struct {
*sql.DB
}
type songHearing struct {
Name string
Date time.Time
}
func InitDB(filepath string) (SongDB, error) {
db, err := sql.Open("sqlite3", filepath)
if err == nil {
if db == nil {
err = errors.New("db is nil")
} else {
_, err = db.Exec(`PRAGMA foreign_keys = ON`)
}
}
return SongDB{db}, err
}
func (db SongDB) CreateSchemaIfNotExists() (err error) {
// id is explicitly used instead of rowid, so that AUTOINCREMENT can be set.
// This ensures, that one can, for example, delete the last added hearing.
commands := [...]string{
`CREATE TABLE IF NOT EXISTS song(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
addedAt TEXT NOT NULL,
CONSTRAINT name_unique UNIQUE(name COLLATE NOCASE)
)`,
`CREATE INDEX IF NOT EXISTS song_name ON song(name)`,
`CREATE TABLE IF NOT EXISTS hearing(
id INTEGER PRIMARY KEY AUTOINCREMENT,
songID INTEGER NOT NULL,
heardAt TEXT NOT NULL,
FOREIGN KEY(songID) REFERENCES song(id)
)`}
tx, err := db.Begin()
defer tx.Rollback()
if err != nil {
return
}
for _, c := range commands {
if _, err = tx.Exec(c); err != nil {
return
}
}
return tx.Commit()
}
// AddSong adds the song with the given name and the current timestamp
// to the database.
//
// Feel free to include the artist's name in the song.
//
// The current timestamp will be stored with the local timezone, to
// enable sorting songs by time of day, even when traveling around
// timezones.
func (db SongDB) AddSong(song string) (err error) {
if len(song) == 0 {
return errors.New("the given song is empty")
}
t := time.Now().Format(time.RFC3339)
_, err = db.Exec(`INSERT INTO song(name, addedAt)
VALUES (?, ?)`, song, t)
return
}
// AddHearing registers that the given song was listened to at the
// current timestamp.
//
// song must exactly match an already existing song from the database.
//
// The current timestamp will be stored with the local timezone, to
// enable sorting hearings by time of day, even when traveling around
// timezones.
func (db SongDB) AddHearing(song string) (err error) {
if len(song) == 0 {
return errors.New("the given song is empty")
}
t := time.Now().Format(time.RFC3339)
_, err = db.Exec(`INSERT INTO hearing(songID, heardAt)
VALUES (
(SELECT id FROM song WHERE name = ? COLLATE NOCASE), ?
)`, song, t)
return
}
// AddHearingAndSongIfNeeded registers that the song was listened to
// and, if necessary, adds the song to the database before that.
func (db SongDB) AddHearingAndSongIfNeeded(song string) error {
if len(song) == 0 {
return errors.New("the given song is empty")
}
err := db.AddSong(song)
if err != nil {
// The sqlite3.ErrConstraintUnique just indicates, that the song
// is already in the database.
sqliteErr, ok := err.(sqlite3.Error)
if !ok || sqliteErr.ExtendedCode != sqlite3.ErrConstraintUnique {
return err
}
}
return db.AddHearing(song)
}
// ListSongsInOrderOfAddition lists all songs in the order they were
// added. Newest additions will be listed first.
func (db SongDB) ListSongsInOrderOfAddition() (songs []string, err error) {
rows, err := db.Query(`SELECT name FROM song ORDER BY id DESC`)
if err != nil {
return
}
return extractSongs(rows)
}
// ListSongsInOrderOfLastHearing lists all songs in the order they were
// last heard. The songs that were heard last will be listed first.
func (db SongDB) ListSongsInOrderOfLastHearing() (songs []string, err error) {
rows, err := db.Query(`SELECT name
FROM (
SELECT songID, MAX(heardAt) heardAt
FROM hearing
GROUP BY (songID)
) sub
INNER JOIN song ON song.id = sub.songID
ORDER BY sub.heardAt DESC`)
if err != nil {
return
}
return extractSongs(rows)
}
// ListFavouriteSongs lists all songs, listing those first, that you
// heard most often.
func (db SongDB) ListFavouriteSongs() (songs []string, err error) {
return db.ListFavouriteSongsOmitting(0)
}
// ListFavouriteSongsOmitting lists songs, listing those first, that
// you heard most often. Songs that were heard within the omit timespan
// before now are not listed.
func (db SongDB) ListFavouriteSongsOmitting(omit time.Duration) (songs []string, err error) {
// FIXME: MAX() is not quite right, because of timezones.
rows, err := db.Query(`SELECT name, MAX(heardAt) FROM hearing
INNER JOIN song ON song.id = hearing.songID
GROUP BY hearing.songID
ORDER BY COUNT(*) DESC`)
if err != nil {
return
}
shs, err := rowsToSongHearings(rows, "", omit)
if err != nil {
return
}
songs = make([]string, len(shs))
for i := range shs {
songs[i] = shs[i].Name
}
return
}
func extractSongs(nameRows *sql.Rows) (songs []string, err error) {
for nameRows.Next() {
var song string
if err = nameRows.Scan(&song); err != nil {
return
}
songs = append(songs, song)
}
return songs, nil
}
// ListFrecentSongs lists songs you lately heard a lot, most frecent first.
func (db SongDB) ListFrecentSongs() (songs []string, err error) {
return db.ListFrecentSongsOmitting(0)
}
// ListFrecentSongsOmitting lists songs you lately heard a lot, most
// frecent first. Songs that were heard within the omit timespan before
// now are not listed.
func (db SongDB) ListFrecentSongsOmitting(omit time.Duration) (songs []string, err error) {
// FIXME: If performance becomes an issue: limit results to last year,
// or so.
rows, err := db.Query(`SELECT name, heardAt FROM hearing
INNER JOIN song ON song.id = hearing.songID`)
if err != nil {
return
}
shs, err := rowsToSongHearings(rows, "", omit)
if err != nil {
return
}
return songHearingsToFrecentSongs(shs), nil
}
// ListSuggestions lists songs that you aften hear before or after
// hearing the given song. Best suggestions first.
func (db SongDB) ListSuggestions(song string) (songs []string, err error) {
return db.ListSuggestionsOmitting(song, 0)
}
// ListSuggestionsOmitting lists songs that you aften hear before or
// after hearing the given song. Songs that were heard within the omit
// timespan before now are not listed. Best suggestions first.
func (db SongDB) ListSuggestionsOmitting(song string, omit time.Duration) (songs []string, err error) {
rows, err := db.Query(`SELECT name, heardAt FROM hearing
INNER JOIN song ON song.id = hearing.songID`)
if err != nil {
return
}
shs, err := rowsToSongHearings(rows, song, omit)
if err != nil {
return
}
return songHearingsToSuggestions(shs, song)
}
func rowsToSongHearings(rows *sql.Rows, ref string, omit time.Duration) (shs []songHearing, err error) {
deadline := time.Now().Add(-omit)
unwantedSongs := make(map[string]bool)
unfilteredSHS := make([]songHearing, 0)
for rows.Next() {
var name string
var dateStr string
var date time.Time
if err = rows.Scan(&name, &dateStr); err != nil {
return
}
if date, err = time.Parse(time.RFC3339, dateStr); err != nil {
return
}
if name != ref && date.After(deadline) {
unwantedSongs[name] = true
} else {
unfilteredSHS = append(unfilteredSHS, songHearing{name, date})
}
}
for _, sh := range unfilteredSHS {
if _, unwanted := unwantedSongs[sh.Name]; !unwanted {
shs = append(shs, sh)
}
}
return
}
// RemoveLastHearing removes the latest hearing. Fails if there is no
// hearing in the database.
func (db SongDB) RemoveLastHearing() (song string, err error) {
rows, err := db.Query(`SELECT hearing.id, name FROM hearing
INNER JOIN song ON hearing.songID = song.id
ORDER BY hearing.id DESC
LIMIT 1`)
if err != nil {
return
}
if rows.Next() == false {
return "", errors.New("no hearing found")
}
var id int64
if err = rows.Scan(&id, &song); err != nil {
return
}
if err = rows.Close(); err != nil {
return
}
r, err := db.Exec(`DELETE FROM hearing WHERE id = ?`, id)
if err != nil {
return
}
n, err := r.RowsAffected()
if err != nil {
return
}
if n != 1 {
err = errors.New("hearing got lost in transit")
}
return
}
// RemoveLastHearingOf removes the latest hearing of the given song.
// Fails if the song was never heard or the song does not exist.
func (db SongDB) RemoveLastHearingOf(song string) (err error) {
r, err := db.Exec(`DELETE FROM hearing WHERE id = (
SELECT hearing.id from hearing
INNER JOIN song ON hearing.songID = song.id
WHERE name = ?
ORDER BY hearing.id DESC
LIMIT 1
)`, song)
if err != nil {
return
}
n, err := r.RowsAffected()
if err != nil {
return
}
if n != 1 {
err = errors.New("no hearing for the song was found")
}
return
}
// RemoveSong removes the song with the given name from the database.
// Fails if there is still an entry in the hearing table, that
// references the song.
func (db SongDB) RemoveSong(song string) (err error) {
r, err := db.Exec(`DELETE FROM song WHERE name = ?`, song)
if err != nil {
return
}
n, err := r.RowsAffected()
if err != nil {
return
}
if n != 1 {
err = errors.New("song not found")
}
return
}
// RemoveLastAddedSong removes the last added song from the database.
// Fails if there is still an entry in the hearing table, that
// references the song.
//
// Returns the removed song's name.
func (db SongDB) RemoveLastAddedSong() (song string, err error) {
rows, err := db.Query(`SELECT id, name FROM song ORDER BY id DESC LIMIT 1`)
if err != nil {
return
}
if rows.Next() == false {
return "", errors.New("no song found")
}
var id int64
if err = rows.Scan(&id, &song); err != nil {
return
}
if err = rows.Close(); err != nil {
return
}
r, err := db.Exec(`DELETE FROM song WHERE id = ?`, id)
if err != nil {
return
}
n, err := r.RowsAffected()
if err != nil {
return
}
if n != 1 {
err = errors.New("song got lost in transit")
}
return
}
// RenameSong renames the given song to newName.
func (db SongDB) RenameSong(song, newName string) (err error) {
if len(newName) == 0 {
return errors.New("the new name is empty")
}
r, err := db.Exec(`UPDATE song SET name = ? WHERE name = ?;`, newName, song)
if err != nil {
return
}
n, err := r.RowsAffected()
if err != nil {
return
}
if n != 1 {
err = errors.New("song not found")
}
return
}