db.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "database/sql"
  4. "log"
  5. _ "github.com/mattn/go-sqlite3"
  6. )
  7. // Make sure the go-sqlite3 is here. Keep the db related things together.
  8. type DBData struct {
  9. DB *sql.DB
  10. User string
  11. }
  12. func (db *DBData) Open(filename string) {
  13. var err error
  14. db.DB, err = sql.Open("sqlite3", filename)
  15. if err != nil {
  16. log.Panicln("Error Opening Sqlite3:", err)
  17. }
  18. // Create the tables (if needed)
  19. db.Create()
  20. }
  21. func (db *DBData) Close() {
  22. db.DB.Close()
  23. }
  24. func (db *DBData) Create() {
  25. _, err := db.DB.Exec(
  26. "CREATE TABLE IF NOT EXISTS settings(username TEXT, setting TEXT, value TEXT, PRIMARY KEY(username, setting));")
  27. if err != nil {
  28. log.Panicln(err)
  29. }
  30. _, err = db.DB.Exec(
  31. "CREATE TABLE IF NOT EXISTS scores ( \"username\" TEXT, \"when\" INTEGER, \"date\" INTEGER, \"hand\" INTEGER, \"won\" INTEGER, \"score\" INTEGER, PRIMARY KEY(\"username\", \"date\", \"hand\"));")
  32. if err != nil {
  33. log.Panicln(err)
  34. }
  35. _, err = db.DB.Exec(
  36. "CREATE TABLE IF NOT EXISTS \"monthly\" ( \"month\" INTEGER, \"username\" TEXT, \"days\" INTEGER, \"hands_won\" INTEGER, \"score\" INTEGER, PRIMARY KEY(\"month\",\"username\") );")
  37. if err != nil {
  38. log.Panicln(err)
  39. }
  40. }
  41. func (db *DBData) GetSetting(setting string, ifMissing string) string {
  42. row := db.DB.QueryRow("SELECT value FROM settings WHERE username=? AND setting=?;", db.User, setting)
  43. var value string
  44. // log.Printf("row: %#v\n", row)
  45. err := row.Scan(&value)
  46. if err != nil {
  47. return ifMissing
  48. }
  49. return value
  50. }
  51. func (db *DBData) SetSetting(setting string, value string) {
  52. _, err := db.DB.Exec("REPLACE INTO settings(username, setting, value) VALUES(?,?,?);", db.User, setting, value)
  53. if err != nil {
  54. log.Panicln("Query SetSetting", err)
  55. }
  56. // log.Printf("SetSetting %s %s = %s\n", db.User, setting, value)
  57. }