diff options
author | Franck Cuny <franck@fcuny.net> | 2021-10-10 12:58:56 -0700 |
---|---|---|
committer | Franck Cuny <franck@fcuny.net> | 2022-06-11 14:32:08 -0700 |
commit | 90ebf54e100fbfd85388b89756718cf71cb69795 (patch) | |
tree | 9fbe277d305c46c9807c098d9a8a81768398e863 /tools/mpd-stats/internal/scrobbler | |
parent | mpd-stats: create and run the scrobbler (diff) | |
download | world-90ebf54e100fbfd85388b89756718cf71cb69795.tar.gz |
scrobbler: add interface to the sqlite3 database
We want to persist the records in a database, so we can extract statistics and an history. The module for the database is straightforward: it opens the database if it exists and return an handler to it. If the database does not exists, we create it and we create the only table we need (records).
Diffstat (limited to 'tools/mpd-stats/internal/scrobbler')
-rw-r--r-- | tools/mpd-stats/internal/scrobbler/db.go | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/tools/mpd-stats/internal/scrobbler/db.go b/tools/mpd-stats/internal/scrobbler/db.go new file mode 100644 index 0000000..a788b4c --- /dev/null +++ b/tools/mpd-stats/internal/scrobbler/db.go @@ -0,0 +1,54 @@ +package scrobbler + +import ( + "database/sql" + "fmt" + "os" + + _ "github.com/mattn/go-sqlite3" +) + +func initdb(dbpath string) error { + if _, err := os.Stat(dbpath); err == nil { + return fmt.Errorf("%s already exists", dbpath) + } + + db, err := sql.Open("sqlite3", dbpath) + if err != nil { + return err + } + defer db.Close() + + sqlStmt := `create table records (id text primary key, + title text, + artist text, + album text, + duration int, + time timestamp + );` + + _, err = db.Exec(sqlStmt) + if err != nil { + return err + } + + return nil +} + +func opendatabase(dbpath string) (*sql.DB, error) { + var err error + _, err = os.Stat(dbpath) + + if err != nil { + if err := initdb(dbpath); err != nil { + return nil, err + } + } + + db, err := sql.Open("sqlite3", dbpath) + if err != nil { + return nil, fmt.Errorf("unable to open database: %s", err) + } + + return db, nil +} |