db.go 1.6 KB

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